[英]can't get Woocommerce billing phone inside input field using jquery
我有一個 CF7 表格,需要獲取Woocommerce 計費電話號碼,並使用 jQuery function 在頁面加載時的電話字段中顯示它。 我在 header 區域使用了這個代碼:
// 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 ) ?>");
});
但它返回原始 php 代碼( <?php echo get_user_meta( get_current_user_id(), 'billing_phone', true )?>
)而不是電話號碼; 當我直接在 Woocommerce 的 php 文件中使用相同的 php 代碼時,它可以正常工作。 我應該怎么做才能通過 jQuery 運行 php 語法?
編輯
為了避免上述問題,我嘗試使用 ajax 獲取數據,但這種方法也不起作用:
在函數中。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' );
在quote.js:
jQuery.ajax({
type:"POST",
url: my_ajax_object.ajax_url,
data: { 'action': 'call_my_ajax_handler' }
})
我還可以做些什么?
這應該可行,由於引號,您會遇到異常
const tel = <?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>;
jQuery(document).ready(function(){
jQuery('#tel').val(tel);
});
或者您可以將單引號替換為雙引號
jQuery(document).ready(function(){
jQuery('#tel').val("<?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>");
});
只需在函數中使用此代碼。子主題的 php 可以獲取客戶電話並在輸入文本字段中顯示:
/* 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' );
注意:JavaScript 應該在頁腳區域。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.