我正在建立一个网站,允许作者创建自定义帖子类型,并可以选择创建X个具有相同内容的额外帖子。在这种情况下,所有内容都是元值。
下面的代码使用相同的元值创建新的附加帖子,但它也创建了一个不需要任何元值的附加帖子。
例如,我创建了一篇文章,并设置了选项来创建3篇具有相同元值的额外文章。我将得到4个额外的职位,其中第四个没有数据。
function kt_bulk_add_inventory( $ID, $post ) {
// Bail if no Quantity provided
if ( ! isset( $_REQUEST[\'acf\'][\'field_55bb25125095a\'] ) || empty( $_REQUEST[\'acf\'][\'field_55bb25125095a\'] ) ) {
return;
}
$qty = $_REQUEST[\'acf\'][\'field_55bb25125095a\'];
$item_data = array(
\'item_wood_type\' => $_REQUEST[\'acf\'][\'field_55795ed866432\'],
\'item_thickness\' => $_REQUEST[\'acf\'][\'field_555be6e572883\'],
\'item_width\' => $_REQUEST[\'acf\'][\'field_555be70972884\'],
\'item_length\' => $_REQUEST[\'acf\'][\'field_555be73a72885\'],
\'item_purchase_order\' => $_REQUEST[\'acf\'][\'field_55795fb753941\'],
);
$wood_type_term = get_term_by( \'id\', (int) $item_data[\'item_wood_type\'], \'wood_type\' );
$tax = array(
\'wood_type\' => $wood_type_term->name
);
$post_data = array(
\'post_status\' => \'publish\',
\'post_type\' => \'inventory\',
\'tax_input\' => $tax
);
$new_items = 0;
remove_action( \'publish_inventory\', \'kt_bulk_add_inventory\', 10, 2 );
while ( 1 <= $qty ) {
$item_id = wp_insert_post( $post_data );
foreach ( $item_data as $key => $value ) {
update_post_meta( $item_id, $key, $value );
}
$qty--;
$new_items++;
}
add_action( \'publish_inventory\', \'kt_bulk_add_inventory\', 10, 2 );
}
add_action( \'publish_inventory\', \'kt_bulk_add_inventory\', 10, 2 );
SO网友:Andrew
你选择的钩子在这里很重要。我成功地选择了最新的钩子wp_insert_post
. 如果其他函数与相同的操作挂钩,则需要考虑它们,因为如果它们也创建/更新帖子,则会再次调用这些挂钩。
法典列出了Post, Page, Attachment, and Category Actions (Admin) 按顺序。
为感兴趣的人编写工作代码。
function kt_bulk_add_inventory( $ID ) {
Global $typenow;
if ( \'inventory\' != $typenow ) {
return;
}
// Bail if no Quantity provided
if ( ! isset( $_REQUEST[\'acf\'][\'field_55bb25125095a\'] ) || empty( $_REQUEST[\'acf\'][\'field_55bb25125095a\'] ) ) {
return;
}
$qty = $_REQUEST[\'acf\'][\'field_55bb25125095a\'];
$item_data = array(
\'item_wood_type\' => $_REQUEST[\'acf\'][\'field_55795ed866432\'],
\'item_thickness\' => $_REQUEST[\'acf\'][\'field_555be6e572883\'],
\'item_width\' => $_REQUEST[\'acf\'][\'field_555be70972884\'],
\'item_length\' => $_REQUEST[\'acf\'][\'field_555be73a72885\'],
\'item_purchase_order\' => $_REQUEST[\'acf\'][\'field_55795fb753941\'],
);
$wood_type_term = get_term_by( \'id\', (int) $item_data[\'item_wood_type\'], \'wood_type\' );
$tax = array(
\'wood_type\' => $wood_type_term->name
);
$post_data = array(
\'post_status\' => \'publish\',
\'post_type\' => \'inventory\',
\'tax_input\' => $tax
);
$new_items = 0;
remove_action( \'wp_insert_post\', \'kt_bulk_add_inventory\', 12, 1 );
while ( 1 < $qty ) {
$item_id = wp_insert_post( $post_data );
foreach ( $item_data as $key => $value ) {
update_post_meta( $item_id, $key, $value );
}
$qty--;
$new_items++;
}
add_action( \'wp_insert_post\', \'kt_bulk_add_inventory\', 12, 1 );
}
add_action( \'wp_insert_post\', \'kt_bulk_add_inventory\', 12, 1 );