20 June 2020

How create and show meta (custom) fields in wordpress posts ?

How create meta (custom) fields in wordpress posts ?




<?php


/**
 * Register meta boxes.
 */
function meta_register_meta_boxes() {
    add_meta_box( 'meta-1', __( 'Custom Field', 'meta' ), 'meta_display_callback', 'contracts' );
}
add_action( 'add_meta_boxes', 'meta_register_meta_boxes' );

/**
 * Meta box display callback.
 *
 * @param WP_Post $post Current post object.
 */
function meta_display_callback( $post ) {
?>


<div class="meta_box">
    <style scoped>
        .meta_box{
            display: grid;
            grid-template-columns: max-content 1fr;
            grid-row-gap: 10px;
            grid-column-gap: 20px;
        }
        .meta_field{
            display: contents;
        }
    </style>
    <p class="meta-options meta_field">
        <label for="meta_author">Author</label>
        <input id="meta_author"
            type="text"
            name="meta_author"
            value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'meta_author', true ) ); ?>">
    </p>
    <p class="meta-options meta_field">
        <label for="meta_published_date">Published Date</label>
        <input id="meta_published_date"
            type="date"
            name="meta_published_date"
           value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'meta_published_date', true ) ); ?>">
    </p>
    <p class="meta-options meta_field">
        <label for="meta_price">Price</label>
        <input id="meta_price"
            type="number"
            name="meta_price"
            value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'meta_price', true ) ); ?>">
    </p>
</div>
<?php
}




/**
 * Save meta box content.
 *
 * @param int $post_id Post ID
 */
function meta_save_meta_box( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( $parent_id = wp_is_post_revision( $post_id ) ) {
        $post_id = $parent_id;
    }
    $fields = [
        'meta_author',
        'meta_published_date',
        'meta_price',
    ];
    foreach ( $fields as $field ) {
        if ( array_key_exists( $field, $_POST ) ) {
            update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
        }
     }
}
add_action( 'save_post', 'meta_save_meta_box' );





How to add custom woocommerce-MyAccount-navigation on woocommerce account page






// Note the low hook priority, this should give to your other plugins the time to add their own items...
add_filter( 'woocommerce_account_menu_items', 'add_my_menu_items', 99, 1 );

function add_my_menu_items( $items ) {
    $my_items = array(
    //  endpoint   => label
        '2nd-item' => __( '2nd Item', 'my_plugin' ),
        '3rd-item' => __( '3rd Item', 'my_plugin' ),
    );

    $my_items = array_slice( $items, 0, 1, true ) +
        $my_items +
        array_slice( $items, 1, count( $items ), true );

    return $my_items;
}

16 June 2020

How to create custom meta boxes on single product page in woocommerce?

Create custom meta boxes on single product page in woocommerce.


/**
 * Display custom field on the front end
 * @since 1.0.0
 */
function wpcodekit_display_custom_field() {
?>
<style>
.custom-field-container {
    float: left;
    justify-content: center;
    align-items: center;
    max-width: 99px;
    padding: 0px 10px;
    text-align: center;
}
img.custom-field-icons {
    margin: auto;
    width: 25px;
    margin-bottom: 0px;
}
.custom-field-outer {
    margin-bottom: 25px;
    float: left;
    width: 100%;
}
.custom_field_title {
    font-size: 12px;
    line-height: 0px !important;
    color: #2d2d2d;
}

.cfwc-custom-field-wrapper {
    line-height: 16px;
}

</style>
<?php

 global $post;
 // Check for the custom field value
 $product = wc_get_product( $post->ID );

 $title_one = $product->get_meta( 'replacement_Days' );
 $title_two = $product->get_meta( 'year_warranty' );
 $title_three = $product->get_meta( 'delivered' );
 echo '<div class="custom-field-outer">';

 if( $title_one ) {
 // Only display our field if we've got a value for the field title
 printf(
 '<div class="custom-field-container"><img src="'.get_stylesheet_directory_uri().'/images/ReturnIcon.png'.'" class="custom-field-icons"><div class="cfwc-custom-field-wrapper"><label for="cfwc-title-field" class="custom_field_title">%s Days Returnable</label></div></div>',
 esc_html( $title_one )
 );
 }


  if( $title_two ) {
 // Only display our field if we've got a value for the field title
 printf(
 '<div class="custom-field-container"><img src="'.get_stylesheet_directory_uri().'/images/Warranty.png'.'" class="custom-field-icons"><div class="cfwc-custom-field-wrapper"><label for="cfwc-title-field" class="custom_field_title">%s</label></div></div>',
 esc_html( $title_two )
 );
 }

 //echo get_stylesheet_directory_uri().'/images/ReturnIcon.png';
  if( $title_three ) {
 // Only display our field if we've got a value for the field title
 printf(
 '<div class="custom-field-container"><img src="'.get_stylesheet_directory_uri().'/images/Lensforu_Delivery.png'.'" class="custom-field-icons"><div class="cfwc-custom-field-wrapper"><label for="cfwc-title-field" class="custom_field_title">%s</label></div></div>',
 esc_html( $title_three )
 );
 }

 echo '</div>';

}
add_action( 'woocommerce_before_add_to_cart_button', 'wpcodekit_display_custom_field' );

How to create custom social share button in wordpress without plugin?

Create custom social share button in wordpress without plugin.


function social_icons_products(){
global $wpdb;
global $post;
 $full_line = get_permalink();
 $slug = basename(get_permalink());



    // $url = str_replace("/", "%2F", $full_line);
    // $url = str_replace(":", "%3A", $url);
    


?>
<style>
.social_icons_container {
    text-align: center;
    align-items: center;
display: inline-flex;
        margin: 0px !important;
}
.font_icons {
padding: 6px 13px 6px 13px;
    cursor: pointer;
font-size: 15px;
    color: black;
    transition: 0.1s all ease-in-out;
}
.font_icons:hover {
    background: black;
    color: white;
}
.share_text {
    margin-bottom: 1px;
    font-size: 16px;
    color: black;
    margin-right: 10px;
}
</style>

<div class="social_icons_container">
<p class="share_text">Share</p>
<a href="<?php echo 'https://www.facebook.com/sharer/sharer.php?href='.$full_line; ?>" >
<div class="font_icons"><i class="fab fa-facebook-f"></i>
</div>
</a>
<a href="<?php echo 'https://twitter.com/intent/tweet?url='.$full_line.'"' ?>" >
<div class="font_icons"><i class="fab fa-twitter"></i>
</div>
</a>
<a href="<?php echo 'https://www.linkedin.com/shareArticle?mini=true&url='.$full_line.'"' ?>" >
<div class="font_icons"><i class="fab fa-linkedin-in"></i>
</div>
</a>
</div>
<?php
}
add_action('woocommerce_share','social_icons_products');


How to create custom wishlist in wordpress without plugin?

Create custom wishlist in wordpress without plugin.


<style>

.wishlist-wrapper {
    font-size: 12px;
    height: 30px;
    display: inline-block;
    line-height: 30px;
    border-radius: 30px;
    background: #f1f1f1;
    padding: 0px 10px;
}

span.wishlist-title {
    float: left;
    margin-right: 5px;
}

span.little-heart {
    float: left;
    display: inline-block;
    margin-top: 5px;
}

.wishlist-wrapper:hover {
    //background: #ff9900;
}

.wishlist-wrapper:hover > span.wishlist-title
{
//color:#fff;
}


.products .wishlist-title
{

display:none;
}

.products .wishlist-wrapper
{
height:40px;
width:40px;
border-radius:40px;
}


.products  span.little-heart {
    float: left;
    display: inline-block;
    margin-top: 11px;
    margin-left: 1px;
}

.added .wishlist-wrapper
{
background:#ff9900;
}

.added span.wishlist-title
{
color:#fff;
}


.product_thumb {
    width: 15%;
    float: left;
}
.wishlist_left_cont {
    float: right;
    width: 85%;
    display: block;
padding: 40px 60px;
}
.full_wishlist_cont {
    background: #fff;
    width: 100%;
    border-bottom: 1px solid #dcdcdc;
    margin: 0 !important;
    display: inline-block;
    box-sizing: border-box;
}

h4.wishlist_title {
    color: #5a5a5a;
    font-family: Titillium -webkit-body;
    font-size: 24px;
    font-weight: 700;
    letter-spacing: 0px;
    margin: 0;
}
p.wishlist_reg_price {
    color: #FF9900;
    font-size: 17px;
    font-family: Titillium -webkit-body;
    font-weight: 600;
    margin: 0;
    letter-spacing: 1px;
}
.wishlist_outer:hover .wishlist_title{
color:#0b3288;
}
span.wishlist_sale_price {
    color: #9a9a9a;
    font-size: 19px;
    font-family: Titillium -webkit-body;
    font-weight: 300;
    letter-spacing: 1px;
}
.remove_wishlist_product {
    display: block;
    color: #cccccc;
    position: absolute;
    top: 28px;
    right: 35px;
    font-size: 17px;
cursor:pointer;
}
.remove_wishlist_product:hover i {
    color: #FF9900;
}
.wishlist_outer{
position:relative;
margin:0px !important;
    width: 100% !important;
    max-width: 100% !important;
}

a.return-to-shop_from_wishlist {
    color: white;
    font-size: 18px;
    font-weight: 400;
    font-family: Titillium -webkit-body;
    display: inline;
    background: #020202;
    padding: 11px 21px;
    border-radius: 6px;
}

.wishlist_status {
    color: black;
    font-size: 19px;
    font-weight: 400;
    font-family: Titillium -webkit-body;
    display: block;
    border-radius: 6px;
}
.wishlist_wrap {
    max-width: 100% !important;
}

.home .products .wishlist-toggle
{
display:none !important;
}

</style>



In function.php





/* wishlist coding */
// Add wishlist to product
add_action('woocommerce_before_shop_loop_item_title','wishlist_toggle',15);
add_action('woocommerce_single_product_summary','wishlist_toggle');
function wishlist_toggle(){
?>
<script>


</script>
<?php
            global $product;
$productid = $product->get_id();
$wishclassname = "removed";
$wstatus = "Add to wishlist";
if(is_user_logged_in()){
global $current_user;
get_currentuserinfo();
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$hasusermeta = get_users('meta_key='.$user_id.'wishlist');
if(empty($hasusermeta)) {
$wishclassname = "removed";
$wstatus = "Add to wishlist";
}
else
{
$current_user_wishlist = get_user_meta( $user_id, $user_id.'wishlist',true);
if(empty($current_user_wishlist))
{
$wishclassname = "removed";
$wstatus = "Add to wishlist";
}else
{
$current_user_wishlist_array = explode( ',', $current_user_wishlist );
if (in_array($productid, $current_user_wishlist_array)) 
  { 
$wishclassname = "added";
$wstatus = "In your wishlist";
  } 
else
  { 
$wishclassname = "removed";
$wstatus = "Add to wishlist";
  }
}
}
//$wishclassname = "removed";
}
else
{
$wishclassname = "removed";
$wstatus = "Add to wishlist";
}
            echo '<a class="wishlist-toggle '.$wishclassname.'" data-product="'.esc_attr($product->get_id()).'" title="'.esc_attr__("Add to wishlist","text-domain").'"><div class="wishlist-wrapper"><span class="wishlist-title">'.$wstatus.'</span><span class="little-heart">'.file_get_contents(get_stylesheet_directory_uri() . '/svgicons/heart.svg').'</span></div></a>';
}



function add_to_wishlist(){
if(is_user_logged_in()){
$productid = $_POST['productid'];
global $current_user;
get_currentuserinfo();
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$hasusermeta = get_users('meta_key='.$user_id.'wishlist');

if(empty($hasusermeta)){
update_user_meta( $user_id, $user_id.'wishlist', $productid);
echo "added"; 
}
else
{
/* ethe chalu coding takdi */
$current_user_wishlist = get_user_meta( $user_id, $user_id.'wishlist',true);
//print_r($current_user_wishlist);
if(empty($current_user_wishlist))
{
update_user_meta( $user_id, $user_id.'wishlist', $productid);
echo "added"; 
}
else
{
$current_user_wishlist_array = explode( ',', $current_user_wishlist );
//print_r($current_user_wishlist_array);
if (in_array($productid, $current_user_wishlist_array)) 
  { 
$current_user_wishlist_array = array_diff($current_user_wishlist_array, array($productid));
$current_user_wishlist_array = implode( ',', $current_user_wishlist_array );
update_user_meta( $user_id, $user_id.'wishlist', $current_user_wishlist_array);
//print_r($current_user_wishlist_array);
echo "removed"; 
  } 
else
  { 
update_user_meta( $user_id, $user_id.'wishlist', $current_user_wishlist.','.$productid);
echo "added"; 
  } 
}
}
}
else
{
echo "redirect";
}

die();
}
add_action("wp_ajax_add_to_wishlist","add_to_wishlist");
add_action("wp_ajax_nopriv_add_to_wishlist","add_to_wishlist");

function wishlist_items(){
if(is_user_logged_in()){
global $current_user;
get_currentuserinfo();
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
//$hasusermeta = get_users('meta_key='.$user_id.'wishlist');
$current_user_wishlist = get_user_meta( $user_id, $user_id.'wishlist',true);
$current_user_wishlist_array = explode( ',', $current_user_wishlist );
//print_r($current_user_wishlist_array);
count($current_user_wishlist_array);
?>
<div class="empty_box"></div>
<div class="wishlist_wrap">
<?php
foreach ($current_user_wishlist_array as $current_user_wishlist_id)
{
$_product = wc_get_product( $current_user_wishlist_id );
if ( has_post_thumbnail( $current_user_wishlist_id ) ) {
                        $attachment_ids[0] = get_post_thumbnail_id( $current_user_wishlist_id );
                         $attachment = wp_get_attachment_image_src($attachment_ids[0], 'full' ); ?> 
<div class="wishlist_outer">
                      <a href="<?php echo get_permalink($current_user_wishlist_id) ?>"> 
  <div class="full_wishlist_cont">
  <div class="product_thumb"> 
  <img src="<?php echo $attachment[0] ; ?>" class="card-image"  />
  </div>
  <div class="wishlist_left_cont">
<h4 class="wishlist_title"><?php echo get_the_title( $current_user_wishlist_id ); ?></h4>
   <div class="wishlist_price_cont">
   <p class="wishlist_reg_price"><?php  echo $_product->get_regular_price(); ?>    <del><span class="wishlist_sale_price"><?php   echo $_product->get_sale_price(); ?></span></del></p>
  </div>
  </div>
  </div>
  </a>
<div class="remove_wishlist_product" data-value="<?php echo $current_user_wishlist_id; ?>" ><i class="fas fa-trash-alt"></i></div>
</div>
                    <?php }
//echo $_product->get_price();
}

echo "</div>";
}
else{
}
}
add_shortcode("wishlist_products","wishlist_items");



In custom.js





jQuery(document).ready(function($){
/* wishlist */



jQuery('.wishlist-toggle').each(function() {
  $(this).click(function(){
  
/*   if($(this).hasClass( "removed" )){
  $(this).addClass("added");
  $(this).removeClass("removed");
  } */
  var $this = $(this);
 //$this.siblings().removeClass();
 if($this.hasClass('removed')){
   $this.removeClass('removed').addClass('added')
   $this.find('.wishlist-title').html('In your wishlist');
 }else{
   $this.removeClass('added').addClass('removed');
   $this.find('.wishlist-title').html('Add to wishlist');
 }

 
var productid = $(this).attr("data-product");

var data = {
'action' : "add_to_wishlist",
'productid' : productid
}
$.post(myajax.ajax_url, data, function(response){
});



});
});

});
jQuery(document).ready(function($){

if ($('.wishlist_wrap').is(':empty')){
  $('.empty_box').html('<p class="wishlist_status">Your wishlist is currently empty.</p><p class=""><a class="return-to-shop_from_wishlist" href="http://localhost/lensforu/shop/">Return to shop</a></p>');
}
jQuery('.remove_wishlist_product').each(function() {

$(this).click(function(){
var productid = $(this).attr("data-value");   
$(this).closest('.wishlist_outer').remove();
  //alert(productid);
 
 
 
var data = {
'action' : "add_to_wishlist",
'productid' : productid
}
$.post(myajax.ajax_url, data, function(response){
$('.wishlist_wrap').length;
if ($('.wishlist_wrap').is(':empty')){
  $('.empty_box').html('<p class="wishlist_status">Your wishlist is currently empty.</p><p class=""><a class="return-to-shop_from_wishlist" href="http://localhost/lensforu/shop/">Return to shop</a></p>');
}
});

  
  });
});
});



10 June 2020

How to create OTP login in woocommerce wordpress?

Create OTP login in woocommerce wordpress.




Note: Use console while using this code.



Note: You can separate jquery and css.








function wooc_extra_register_fields() {?>
       <p class="form-row form-row-wide">
       <label for="reg_billing_phone"><?php _e( 'Phone', 'woocommerce' ); ?><span class="required">*</span></label>
       <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php esc_attr_e( $_POST['billing_phone'] ); ?>" />
       </p>
   
       <?php
 }
 add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );




 function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) {

if ( isset( $_POST['billing_phone'] ) ) {
   $hasPhoneNumber= get_users('meta_value='.$_POST['billing_phone']);
   if ( !empty($hasPhoneNumber)) {
     $validation_errors->add( 'billing_phone_error', __( '<strong>Error</strong>: Mobile number is already used!.', 'woocommerce' ) );
   }
}
 
         return $validation_errors;
}
add_action( 'woocommerce_register_post', 'wooc_validate_extra_register_fields', 10, 3 );




 /**
* Below code save extra fields.
*/
function wooc_save_extra_register_fields( $customer_id ) {
    if ( isset( $_POST['billing_phone'] ) ) {
                 // Phone input filed which is used in WooCommerce
                 update_user_meta( $customer_id, 'billing_phone', sanitize_text_field( $_POST['billing_phone'] ) );
          }
 
 

}
add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );


function set_otp_cookies(){

$customfield = $_POST['phone_number'];
if(empty($customfield)){

$success = "not_exist";
$otp = 'null';
//return false;
die();


}


 $cookie_otp = $_COOKIE[$customfield];

 $UsermetaData = get_users('meta_value='.$customfield);

//print_r($UsermetaData);
foreach($UsermetaData as $userdata)
{
$billing_phone_num = $userdata->billing_phone;
$user = $userdata->ID;


}


if($billing_phone_num==$customfield){


$random_otp = (rand(55555, 99999));
// set cookie for 5 mintues 500/60=5
setcookie($customfield, $random_otp,time()+500,'/');
setcookie('phone_number', $customfield,time()+500,'/');
$_COOKIE[$customfield];
$_COOKIE[$phone_number];
$success = "true";
$otp = $random_otp;
}

else{

$success = "flase";
$otp = $cookie_otp;

}


echo json_encode(array($customfield,$success,$otp));
die();

}
add_action('wp_ajax_set_otp_cookies', 'set_otp_cookies');
add_action('wp_ajax_nopriv_set_otp_cookies', 'set_otp_cookies');


function otp_form(){
$slug = basename(get_permalink());
?>
<style>

.change_number{

color:Red;
cursor:pointer;
}


</style>
<script>
jQuery(document).ready(function($)
{
//$(".set_otp").click(function(e) {
jQuery(document).on('click', '.set_otp', function(e){
  e.preventDefault();

var ajaxurl = $(".ajaxurl").val();
var phone_number = $(".phone_number").val();

if(phone_number=='')
{

  $(".phone_number").focus();

}
else{


var slug = $(".slug").val();
var data = {
  'action': 'set_otp_cookies',
  'phone_number': phone_number,
  'slug': slug,
};

jQuery.post(ajaxurl, data, function(response) {
//$('.otp').val(response);
//$('.woocommerce').prepend(response);
  var result = $.parseJSON(response);
var customfield = result[0];
//alert(customfield);
var success = result[1];
var otp = result[2];
$('.phone_number').val(customfield);
//alert(otp);
console.log(response);
if(success=='true'){

$('.otp_form').html('<input type="hidden" name="phone_number" class="phone_number" value="'+phone_number+'"><input type="hidden" name="slug" class="slug" value="<?php echo $slug; ?>"><span>Please enter the OTP sent to<br><span class="sent_number">'+customfield+'</span><span class="change_number"> Change</span></span><input type="text" name="otp" class="otp" value=""><input type="submit" name="otp_submit" Value="Submit">');


}
else{

// alert('not exist');

$('.otp_form').html('<span>Account not Exists!</span> <span class="change_number">Change Number</span>');

}
});

}

});



jQuery(document).on('click', '.change_number', function(){

//alert('hello');
$('.otp_form').html('<label>Enter Phone number <span class="required">*</span></label><input type="text" name="phone_number" class="phone_number"><input type="hidden" name="slug" class="slug" value="<?php echo $slug; ?>"><input type="hidden" class="ajaxurl" value="<?php echo admin_url( "admin-ajax.php" ) ;?>"><input type="submit" name="set_otp" class="set_otp" Value="Send Otp">');

});

});

</script>
<form action="" method="post">
<div class="otp_form">
<label>Enter Phone number <span class="required">*</span></label>
<input type="text" name="phone_number" class="phone_number">
<input type="hidden" name="slug" class="slug" value="<?php echo $slug; ?>">
<input type="hidden" class="ajaxurl" value="<?php echo admin_url( 'admin-ajax.php' ) ;?>">
<input type="submit" name="set_otp" class="set_otp" Value="Send Otp">
<!--<input type="text" name="otp" class="otp" value="">
<input type="submit" name="otp_submit" Value="Submit">--->
</div>
</form>
<?php
}
add_action('woocommerce_login_form_end','otp_form');



function otp_login(){

if(isset($_POST['otp_submit'])){

$customfield = $_POST['phone_number'];
//$customfield = $_COOKIE['phone_number'];
$slug_name = $_POST['slug'];
$otp = $_POST['otp'];
$cookie_name = $customfield;
$cookie_otp = $_COOKIE[$customfield];

//$cookie_name = 'otp';
$cookie_otp = $_COOKIE[$cookie_name];
$UsermetaData = get_users('meta_value='.$customfield);

//print_r($UsermetaData);
foreach($UsermetaData as $userdata)
{
$billing_phone_num = $userdata->billing_phone;
$user = $userdata->ID;

}

if(!empty($customfield) && $billing_phone_num==$customfield && !empty($otp) && $otp==$cookie_otp){


if(is_null($user)){
wc_add_notice( 'You must enter registered phone number for otp!', 'error' );

return false;
}



if(!empty($user))
{
global $wpdb;
global $post;

if($slug_name=='checkout')
{

if (!is_wp_error($user))
{

wp_clear_auth_cookie();
wp_set_current_user($user);
wp_set_auth_cookie($user);
setcookie($cookie_name, "", time()-60, '/');
setcookie("phone_number", "", time()-60, '/');
$redirect_to = wc_get_checkout_url();
wp_safe_redirect( wc_get_checkout_url() );
exit();
}
return $user;
}
else

{


if (!is_wp_error($user))
{
wp_clear_auth_cookie();
wp_set_current_user($user);
wp_set_auth_cookie($user);
setcookie($cookie_name, "", time()-60, '/');
setcookie("phone_number", "", time()-60, '/');
$redirect_to = user_admin_url();
wp_safe_redirect( user_admin_url() );
exit();
}
return $user;


}

}




}
elseif(empty($customfield) && empty($otp))
{

wc_add_notice( 'You must enter registered phone number for otp!', 'error' );
return false;
}
elseif(empty($customfield) && !empty($otp))
{

wc_add_notice( 'You must enter registered phone number for otp!', 'error' );
return false;
}


elseif(empty($otp))
{

wc_add_notice( 'You must enter correct otp number!', 'error' );
return false;
}
elseif($otp!==$cookie_otp)
{

wc_add_notice( 'You must enter correct otp number!', 'error' );
return false;
}
else{
wc_add_notice( 'You must enter registered phone number for otp!', 'error' );
return false;


}




}
}
add_action('init','otp_login');



function add_billing_mobile_phone_to_edit_account_form()
 {
    $user = wp_get_current_user();
    ?>
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="billing_phone"><?php _e( 'Mobile phone', 'woocommerce' ); ?> <span class="required">*</span></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--phone input-text" name="billing_phone" id="billing_phone" value="<?php echo esc_attr( $user->billing_phone ); ?>" />
</p>
    <?php
}
add_action( 'woocommerce_edit_account_form_start', 'add_billing_mobile_phone_to_edit_account_form' );


// Check and validate the mobile phone

function billing_mobile_phone_field_validation( $args )
{
if ( isset( $_POST['billing_phone'] ) )
{
   
$hasPhoneNumber= get_users('meta_value='.$_POST['billing_phone']);
global $current_user;
get_currentuserinfo();
$current_user_id = $current_user->ID;
$billing_phone = get_user_meta( $current_user_id, 'billing_phone', true );
   if ( !empty($hasPhoneNumber) && $billing_phone !== $_POST['billing_phone'])
{
$args->add( 'billing_phone_error', __( '<strong>Error</strong>: Mobile number is already used!.', 'woocommerce' ) );
}
}
}
add_action( 'woocommerce_save_account_details_errors','billing_mobile_phone_field_validation', 20, 1 );

// Save the mobile phone value to user data

function my_account_saving_billing_mobile_phone( $user_id )
{
if( isset($_POST['billing_phone']) && ! empty($_POST['billing_phone']) )
        update_user_meta( $user_id, 'billing_phone', sanitize_text_field($_POST['billing_phone']) );
}

add_action( 'woocommerce_save_account_details', 'my_account_saving_billing_mobile_phone', 20, 1 );



function show_login_option()
{
$slug = basename(get_permalink());
if($slug=='checkout')
{
if ( is_user_logged_in() )
{


}
else
{
?>
<script>
jQuery(document).ready(function($)
{
  $(window).load(function() {

$('.showlogin').click();
//alert('hello');
});
});

</script>

<?php
}
}
}
add_action('wp_head','show_login_option');



09 June 2020

How to create login with phone number in woocommerce wordpress?

Create login with phone number in woocommerce wordpress.



function wooc_extra_register_fields() {?>
       <p class="form-row form-row-wide">
       <label for="reg_billing_phone"><?php _e( 'Phone', 'woocommerce' ); ?><span class="required">*</span></label>
       <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php esc_attr_e( $_POST['billing_phone'] ); ?>" />
       </p>
   
       <?php
 }
 add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );




 function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) {

if ( isset( $_POST['billing_phone'] ) ) {
   $hasPhoneNumber= get_users('meta_value='.$_POST['billing_phone']);
   if ( !empty($hasPhoneNumber)) {
     $validation_errors->add( 'billing_phone_error', __( '<strong>Error</strong>: Mobile number is already used!.', 'woocommerce' ) );
   }
}
 
         return $validation_errors;
}
add_action( 'woocommerce_register_post', 'wooc_validate_extra_register_fields', 10, 3 );




 /**
* Below code save extra fields.
*/
function wooc_save_extra_register_fields( $customer_id ) {
    if ( isset( $_POST['billing_phone'] ) ) {
                 // Phone input filed which is used in WooCommerce
                 update_user_meta( $customer_id, 'billing_phone', sanitize_text_field( $_POST['billing_phone'] ) );
          }
 
 

}
add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );




function otp_form(){
$slug = basename(get_permalink());
?>
<form action="" method="post">
<label>Enter Phone number <span class="required">*</span></label>
<input type="text" name="phone_number" class="phone_number">
<input type="hidden" name="slug" class="slug" value="<?php echo $slug; ?>">
<input type="submit" name="otp_submit" Value="Send Otp">
</form>
<?php
}
add_action('woocommerce_login_form_end','otp_form');



function otp_login(){

if(isset($_POST['otp_submit'])){

$customfield = $_POST['phone_number'];

$slug_name = $_POST['slug'];

if(!empty($customfield)){

$UsermetaData = get_users('meta_value='.$customfield);
//print_r($UsermetaData);
foreach($UsermetaData as $userdata)
{

$user = $userdata->ID;

}
if(is_null($user)){
wc_add_notice( 'You must enter registered phone number for otp!', 'error' );
return false;
}



if(!empty($user))
{
global $wpdb;
global $post;

if($slug_name=='checkout')
{

if (!is_wp_error($user))
{

wp_clear_auth_cookie();
wp_set_current_user($user);
wp_set_auth_cookie($user);
$redirect_to = wc_get_checkout_url();
wp_safe_redirect( wc_get_checkout_url() );
exit();
}
return $user;
}
else

{


if (!is_wp_error($user))
{
wp_clear_auth_cookie();
wp_set_current_user($user);
wp_set_auth_cookie($user);
$redirect_to = user_admin_url();
wp_safe_redirect( user_admin_url() );
exit();
}
return $user;


}

}
}
else
{

wc_add_notice( 'You must enter registered phone number for otp!', 'error' );
return false;
}
}
}
add_action('init','otp_login');




function add_billing_mobile_phone_to_edit_account_form()
 {
    $user = wp_get_current_user();
    ?>
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="billing_phone"><?php _e( 'Mobile phone', 'woocommerce' ); ?> <span class="required">*</span></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--phone input-text" name="billing_phone" id="billing_phone" value="<?php echo esc_attr( $user->billing_phone ); ?>" />
</p>
    <?php
}
add_action( 'woocommerce_edit_account_form_start', 'add_billing_mobile_phone_to_edit_account_form' );


// Check and validate the mobile phone

function billing_mobile_phone_field_validation( $args )
{
if ( isset( $_POST['billing_phone'] ) )
{
   
$hasPhoneNumber= get_users('meta_value='.$_POST['billing_phone']);
global $current_user;
get_currentuserinfo();
$current_user_id = $current_user->ID;
$billing_phone = get_user_meta( $current_user_id, 'billing_phone', true );
   if ( !empty($hasPhoneNumber) && $billing_phone !== $_POST['billing_phone'])
{
$args->add( 'billing_phone_error', __( '<strong>Error</strong>: Mobile number is already used!.', 'woocommerce' ) );
}
}
}
add_action( 'woocommerce_save_account_details_errors','billing_mobile_phone_field_validation', 20, 1 );

// Save the mobile phone value to user data

function my_account_saving_billing_mobile_phone( $user_id )
{
if( isset($_POST['billing_phone']) && ! empty($_POST['billing_phone']) )
        update_user_meta( $user_id, 'billing_phone', sanitize_text_field($_POST['billing_phone']) );
}

add_action( 'woocommerce_save_account_details', 'my_account_saving_billing_mobile_phone', 20, 1 );



function show_login_option()
{
$slug = basename(get_permalink());
if($slug=='checkout')
{
if ( is_user_logged_in() )
{


}
else
{
?>
<script>
jQuery(document).ready(function($)
{
  $(window).load(function() {

$('.showlogin').click();
//alert('hello');
});
});

</script>

<?php
}
}
}
add_action('wp_head','show_login_option');


How to show wordpress error messages in woocommer and wordpress? || wc_add_notice Function

How to show wordpress error messages in woocommer and wordpress? ||  wc_add_notice Function


if(is_null($user)){
wc_add_notice( 'You must enter registered phone number for otp!', 'error' );
return false;
}

How to customize login process in woocommerce and wordpress ?

Customize login process in woocommerce and wordpress.



$customfield = $_POST['phone_number'];


$UsermetaData = get_users('meta_value='.$customfield); //print_r($UsermetaData); foreach($UsermetaData as $userdata){ $user = $userdata->ID; }

if (!is_wp_error($user))
{
    wp_clear_auth_cookie();
    wp_set_current_user($user);
    wp_set_auth_cookie($user);
    $redirect_to = user_admin_url();
    wp_safe_redirect( user_admin_url() );
    exit();
}
return $user;

How to get page name(template) from url in wordpress?

Get page name(template) from url in wordpress.


global $wpdb;
global $post;

$slug = basename(get_permalink());

How to show automatically Login box on checkout page in woocommerce?

If user is not login in woocommerce on checkout page then checkout login option will automatically enable to login.


Login with checkout page login option in woocommerce




function show_login_option(){

 $slug = basename(get_permalink());

 if($slug=='checkout'){
if ( is_user_logged_in() ) {

// echo '<script>alert("your are login");</script>';

} else {
 ?>
 <script>
jQuery(document).ready(function($) {
  $(window).load(function() {

$('.showlogin').click();
//alert('hello');


});
});

  </script>

  <?php
}
}
}
add_action('wp_head','show_login_option');


08 June 2020

warning cannot modify header information - headers already sent by wordpress.

warning cannot modify header information - headers already sent by wordpress.


Add this code in wp-config.php on the first line:

ob_start();
error_reporting(0);

05 June 2020

Hide wordpress tool bar

Hide wordpress tool bar




add_filter('show_admin_bar', '__return_false');

Login with Phone number in Woocommerce WordPress

Login with Phone number in Woocommerce WordPress



function wooc_add_phone_number_field() {
    return apply_filters( 'woocommerce_forms_field', array(
        'wooc_user_phone' => array(
            'type'        => 'text',
            'label'       => __( 'Phone Number', ' woocommerce' ),
            'placeholder' => __( 'Your phone number', 'woocommerce' ),
            'required'    => true,
        ),
    ) );
}
add_action( 'woocommerce_register_form', 'wooc_add_field_to_registeration_form', 15 );
function wooc_add_field_to_registeration_form() {
    $fields = wooc_add_phone_number_field();
    foreach ( $fields as $key => $field_args ) {
        woocommerce_form_field( $key, $field_args );
    }
}

add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );
function wooc_save_extra_register_fields( $customer_id ) {
    if (isset($_POST['wooc_user_phone'])){
        update_user_meta( $customer_id, 'wooc_user_phone', sanitize_text_field( $_POST['wooc_user_phone'] ) );
    }
}

function wooc_get_users_by_phone($phone_number){
    $user_query = new \WP_User_Query( array(
        'meta_key' => 'wooc_user_phone',
        'meta_value' => $phone_number,
        'compare'=> '='
    ));
    return $user_query->get_results();
}

add_filter('authenticate','wooc_login_with_phone',30,3);
function wooc_login_with_phone($user, $username, $password ){
    if($username != ''){
        $users_with_phone = wooc_get_users_by_phone($username);
        if(empty($users_with_phone)){
            return $user;
}
$phone_user = $users_with_phone[0];

if ( wp_check_password( $password, $phone_user->user_pass, $phone_user->ID ) ){
return $phone_user;
}
    }
    return $user;
}

add_filter( 'gettext', 'wooc_change_login_label', 10, 3 );
function wooc_change_login_label( $translated, $original, $domain ) {
    if ( $translated == "Username or email address" && $domain === 'woocommerce' ) {
        $translated = "Username or email address or phone";
    }
    return $translated;
}

How to add re-captcha v3 on all Elementor forms using coding?

 Add re-captcha v3 on all Elementor forms using coding add_action('wp_footer',function(){     ?> <script src="https://www...