无法使用 jquery 在输入字段中获取 Woocommerce 账单 phone

can't get Woocommerce billing phone inside input field using jquery

我有一个 CF7 表格,需要获取 Woocommerce 账单 phone 号码 并使用 [=42= 在页面加载时将其显示在 phone 字段中] 功能。我在页眉区域使用了这段代码:

// 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 ) ?>");
    });

但它 returns 原始 php 代码 ( <?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?> ) 而不是 phone 数字;当我直接在 Woocommerce 的 php 文件中使用相同的 php 代码时,它可以正常工作。我应该如何通过 jQuery?

对 运行 一个 php 语法进行处理

编辑


为了避免上述问题,我尝试使用ajax获取数据,但这种方法也不起作用:

在 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' );

在 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 ) ?>");
    });

只需在子主题的 functions.php 中使用此代码即可获取客户 phone 并显示在输入文本字段中:

/* 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 应该在页脚区域。