【发布时间】:2019-01-15 18:48:14
【问题描述】:
我正在尝试将在数组中找到的一行 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 的变量转储
array (size=4)
0 => int 1
1 => int 2
2 => int 3
3 => int 4
$qty 的变量转储
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,
));
}
}
}
【问题讨论】:
-
您能否提供
$qty的var_dump()(或等效项)导致您的期望与现实之间存在这种差异? -
我已经编辑了我的问题
-
你还是没有提供
$qty的var_dump()。 -
抱歉,我现在已经包含了
-
如果这正是您的代码和输出,那么肯定有问题。难道是当您在 save_post 上触发另一个插入数据库的操作时?