繁体   English   中英

Foreach add wpdb->insert 添加意外的行数

[英]Foreach add wpdb->insert adding unexpected number of rows

我正在尝试将在数组中找到的一行 foreach 值插入到 wordpress 数据库中。 但是,在保存新帖子时,我在表格中得到了意外的行数?

例如,如果我将最大条目数设置为 4 并单击保存,我最终会得到 6 行?

add_action( 'save_post', 'mp_sync_on_product_save', 10, 1 );
function mp_sync_on_product_save( $product_id ) {
    global $wpdb;
    $product = wc_get_product( $product_id );
    $qty = get_field('maximum_entries', $product_id);
    print_r($qty);
    $array = range(1, $qty);

    foreach ($array as $ticket) {
     $wpdb->insert('wp_tickets', array(
        'ticket_number' => $ticket,
     ));
    }
}

$array 的 var 转储

array (size=4)
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4

$qty 的 var 转储

string '4'

将插入的行输出到 wp_tickets

id--order_id--ticket_number--lottery_id 
44----0----------1----------------0
45----0----------0----------------0
46----0----------1----------------0
47----0----------2----------------0
48----0----------3----------------0
49----0----------4----------------0

更新代码

add_action('save_post', 'my_acf_save_post', 100, 3);
function my_acf_save_post( $post_id, $post, $update ) {

        global $wpdb;
        global $post;

        if( ! ( wp_is_post_revision( $post_id) || wp_is_post_autosave( $post_id ) ) ) {

        $qty = wc_clean( $_POST['_max_tickets']);
    $array = range(1, $qty);

    foreach ($array as $ticket) {
     $wpdb->insert('wp_tickets', array(
         'ticket_number' => $ticket,
         'lottery_id' => $post_id,
     ));
    }

        }
}

这是因为根据 wordpress 核心功能 save_post 钩子触发多次(例如:自动保存),请参阅此处的文档

所以第一次 $qty 为空。所以 $array 值将是

数组(2) { [0]=> int(1) [1]=> int(0) }

您需要按如下方式重写代码。

add_action( 'save_post', 'mp_sync_on_product_save', 11, 1 );
function mp_sync_on_product_save( $product_id ) {
    global $wpdb;
    if( ! ( wp_is_post_revision( $product_id) || wp_is_post_autosave( $product_id ) ) ) {
        $product = wc_get_product( $product_id );
        $qty = get_field('maximum_entries', $product_id);

        $array = range(1, $qty);

        foreach ($array as $ticket) {
         $wpdb->insert('wp_tickets', array(
            'ticket_number' => $ticket,
         ));
        }
    }
}

注意:保持 add_action 优先级大于 10,因为它的默认优先级

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM