skip to Main Content

I have a CF7 form and need to get Woocommerce billing phone number and display it inside phone field on page load using jQuery function. I used this code in header area:

// Get billing_phone_number On Quote Form

jQuery(document).ready(function(){
        jQuery('#mk-order-tel').val("<?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>");
    });

But it returns raw php code ( <?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?> ) instead of phone number; when I use same php code directly in php files of Woocommerce it works correctly. What should I do to run a php syntax through the jQuery?

EDIT


To escape of above issue, I tried to get data by using ajax but this method does not work too:

in functions.php :

/* Get Customer Phone Number */

function my_ajax_handler(){
    global $woocommerce;
    $phone = get_user_meta( get_current_user_id(), 'billing_phone', true );
     ?>
    <script type="text/javascript">
    jQuery( function($){
    jQuery('#mk-order-tel').val("<?php echo json_encode($phone); ?>");
    });
    </script>
    <?php
}

add_action( 'wp_ajax_call_my_ajax_handler', 'my_ajax_handler' );
add_action( 'wp_ajax_nopriv_call_my_ajax_handler', 'my_ajax_handler' );


function my_quote_scripts() {
  wp_enqueue_script( 'my-ajax-script', get_stylesheet_directory_uri() . '/js/quote.js', array('jquery') );
  wp_localize_script( 'my-ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_quote_scripts' );

in quote.js :

jQuery.ajax({
    
    type:"POST",
    url: my_ajax_object.ajax_url,
    data: { 'action': 'call_my_ajax_handler' }
    
})

What else can I do ?

2

Answers


  1. Chosen as BEST ANSWER

    Simply using this code in functions.php of child theme can fetch customer phone and display inside input text field :

    /* Get Customer Phone Number On Quote Form */
    
    function my_jquery_var() {
        if ( $yourtel = get_user_meta( get_current_user_id(), 'billing_phone', true ) ) { 
            
            echo '<script type="text/javascript">
            var yourTel = "' . $yourtel . '";
            document.getElementById("mk-order-tel").value = yourTel;
            </script>' . "n";
            
        }
    }
    add_action( 'wp_footer', 'my_jquery_var' );
    

    Note: JavaScript should be in footer area.


  2. This should work, you’re getting an exception because of quotes

    const tel = <?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>;
    jQuery(document).ready(function(){
       jQuery('#tel').val(tel);
    });
    

    Or you can just replace single quotes to double

    jQuery(document).ready(function(){
            jQuery('#tel').val("<?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>");
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search