You are not using the right way and hooks. Also the right custom field meta key should be _wc_acof_3
when using WooCommerce Admin Custom Order Fields plugin.
So try the following instead:
// Add a bulk action to Orders bulk actions dropdown
add_filter( 'bulk_actions-edit-shop_order', 'decrease_meals_orders_bulk_actions' );
function decrease_meals_orders_bulk_actions( $bulk_actions ) {
$bulk_actions['decrease_meals'] = 'Decrease Number of Meals by 1';
return $bulk_actions;
}
// Process the bulk action from selected orders
add_filter( 'handle_bulk_actions-edit-shop_order', 'decrease_meals_bulk_action_edit_shop_order', 10, 3 );
function decrease_meals_bulk_action_edit_shop_order( $redirect_to, $action, $post_ids ) {
if ( $action === 'decrease_meals' ){
$processed_ids = array(); // Initializing
foreach ( $post_ids as $post_id ) {
// Get number of meals
$nb_meal = (int) get_post_meta( $post_id, '_wc_acof_3', true );
// Save the decreased number of meals ($meals - 1)
update_post_meta( $post_id, '_wc_acof_3', $nb_meal - 1 );
$processed_ids[] = $post_id; // Adding processed order IDs to an array
}
// Adding the right query vars to the returned URL
$redirect_to = add_query_arg( array(
'decrease_meals' => '1',
'processed_count' => count( $processed_ids ),
'processed_ids' => implode( ',', $processed_ids ),
), $redirect_to );
}
return $redirect_to;
}
// Display the results notice from bulk action on orders
add_action( 'admin_notices', 'decrease_meals_bulk_action_admin_notice' );
function decrease_meals_bulk_action_admin_notice() {
global $pagenow;
if ( 'edit.php' === $pagenow && isset($_GET['post_type'])
&& 'shop_order' === $_GET['post_type'] && isset($_GET['decrease_meals']) {
$count = intval( $_REQUEST['processed_count'] );
printf( '<div class="notice notice-success fade is-dismissible"><p>' .
_n( 'Decreased meals for %s Order.',
'Decreased meals for %s Orders.',
$count,
'woocommerce'
) . '</p></div>', $count );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…