如何通过 javascript 使用 WordPress table 的 SQL 查询填充表单字段

How to populate a form field via javascript with an SQL query of WordPress table

我有一个 Contact 7 表单,其中隐藏字段标记为 confirmation_number。我需要用 SQL 查询填充该字段。

这是我的 SQL 查询

select count(*)
from wp_postmeta
where meta_value = "used"

这是我在 functions.php

中输入的代码
add_action( 'wp_footer', 'add_confirmation_number' );
function add_confirmation_number() {
  $page_id = get_the_ID();
  if($page_id===11699 || $page_id===11709 || $page_id===11710 ||$page_id===11729 ){
        $wpcf7 = WPCF7_ContactForm::get_current();
        global $wpdb;
        $confirmation_number = $wpdb->get_var(("SELECT count(*) FROM $wpdb->wp_postmeta  WHERE meta_value = 'used' "));
        return $confirmation_number;
    ?>

    <script type="text/javascript">
            document.getElementById('confirmation-number').value = <?php echo $confirmation_number ?>;
    </script>

    <?php
  }
}

我遇到错误 Undefined property: wpdb::

但我已尽一切努力修复此语法,但没有任何效果。我也不确定我是否在使用 $wpdb 正确。我是一名崭露头角的 Wordpress 开发人员,如有任何帮助,我们将不胜感激!

我看到了一些东西。一是您的脚本可能永远不会加载,因为您有 as return $confirmation_number 这将停止函数的传播。第二个是 $wpdb->table_name 属性不包含前缀。 postmetatable$wpdb->postmeta。您还可以使用 $wpdb->prefix 将前缀添加到尚未添加到全局 $wpdb 对象的 table,如果您需要访问这些

我也清理了一些东西,但是删除 return 语句,并将 $wpdb->wp_postmeta 更改为 $wpdb->postmeta 应该就足够了。

add_action( 'wp_footer', 'add_confirmation_number' );
function add_confirmation_number() {
    $confirmation_page_ids = array( 11699, 11709, 11710, 11729 );

    if( in_array(get_the_ID(), $confirmation_page_ids) ){
        global $wpdb;
        $wpcf7 = WPCF7_ContactForm::get_current(); // Is this necessary? No other calls to $wpcf7 below

        $sql = "
            SELECT count(*)
            FROM   $wpdb->postmeta
            WHERE  meta_value = 'used'
        ";

        $confirmation_number = $wpdb->get_var( $sql );

        if( $confirmation_number !== null ){
            printf( '<script type="text/javascript">
                document.getElementById("confirmation-number").value = %d;
            </script>', absint($confirmation_number) );
        }
    }
}

更改这行代码:

$confirmation_number = $wpdb->get_var(("SELECT count(*) FROM $wpdb->wp_postmeta  WHERE meta_value = 'used' "));

收件人:

$confirmation_number = $wpdb->get_var(("SELECT count(*) FROM $wpdb->postmeta  WHERE meta_value = 'used' "));

A​​slo return $confirmation_number; 不应该出现。