I'm building a site which allows authors to create a custom post type, and optionally elect to create X amount of additional posts with the same content. In this case all the content is meta values.
The following code creates new additional posts with the same meta values, but it is also creating an additional unwanted post without any meta values.
For example, I create a post and set the option to create 3 additional posts with the same meta values. I will get 4 additional posts, the fourth of which has no data.
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 );