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
Simply using this code in functions.php of child theme can fetch customer phone and display inside input text field :
Note: JavaScript should be in footer area.
This should work, you’re getting an exception because of quotes
Or you can just replace single quotes to double