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?
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 ) ?>");
});
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.