在带有 WP All Import 的 WooCommerce 中,我使用以下代码来减少产品库存数量,但我得到的库存数量为 0(因此不起作用):
function reduce_stock_based_on_custom_field( $product_id, $xml, $update ) {
// Get the value of custom field 'bmind_stock'
$bmind_stock = get_post_meta( $product_id, 'bmind_stock', true );
// Check if 'bmind_stock' is 0 and reduce stock accordingly
if ( $bmind_stock === 0 ) {
// Get current stock
$current_stock = get_post_meta( $product_id, '_stock', true );
// Calculate new stock after reduction (e.g., reducing by 1)
$new_stock = ($current_stock) - 1;
// Update product stock
wc_maybe_reduce_stock_levels( $product_id, '_stock', $new_stock );
}
}
add_action( 'pmxi_saved_post', 'reduce_stock_based_on_custom_field', 10, 3 );
例如:如果产品库存数量为 6,并且如果我的
bmind_stock
自定义字段值为 0,则我需要将产品库存设置为 5,因此将其减少到 1。
请尝试以下简化的代码修订版:
add_action( 'pmxi_saved_post', 'reduce_product_stock_based_on_custom_field', 10 );
function reduce_product_stock_based_on_custom_field( $post_id ) {
// Check if 'bmind_stock' is 0 and reduce stock accordingly
if ( get_post_meta($post_id, 'bmind_stock', true) == 0 ) {
// Update calculated stock after reduction (e.g., reducing by 1)
update_post_meta($post_id, '_stock', get_post_meta($post_id, '_stock', true) - 1 );
}
}
应该可以...
如果
'bmind_stock'
自定义字段是临时使用的,您可以在库存更新行之后将其删除,使用delete_post_meta($post_id, 'bmind_stock');
…
文档:wp-all-import-action-reference/all-import/pmxi_saved_post.php