WooCommerce中如何读取可变产品变体库存并存储到自定义表
WooCommerce产品及变体库存存入自定义表实现方案
原有代码问题说明
- 仅读取了主产品库存,未遍历可变产品下的所有变体数据
get_post_meta未传第三个参数true,返回的是数组而非库存数值transition_post_status触发时机早于post_meta写入,大概率读取不到刚生成的库存数据- 存在变量拼写错误(
$prodcut_qty应为$product_qty) - 插入自定义表时缺失表结构要求的
log_date字段赋值
完整实现代码
选择你提到的added_post_meta钩子实现,确保库存meta写入完成后再执行操作,兼容WooCommerce 5.5.2版本:
// 绑定库存meta新增钩子,需要兼容库存更新场景可额外绑定updated_post_meta钩子 add_action( 'added_post_meta', 'insert_stock_to_custom_table', 10, 4 ); function insert_stock_to_custom_table( $meta_id, $post_id, $meta_key, $meta_value ) { // 仅响应库存meta写入操作,避免多余执行 if ( $meta_key !== '_stock' ) { return; } $post = get_post( $post_id ); // 仅处理产品、产品变体两种内容类型 if ( ! in_array( $post->post_type, [ 'product', 'product_variation' ] ) ) { return; } global $wpdb, $current_user; wp_get_current_user(); $user_id = $current_user->ID; // 仅首次发布产品时写入,不需要该限制可删除以下3行判断 $parent_post_id = $post->post_type === 'product_variation' ? $post->post_parent : $post_id; $parent_post = get_post( $parent_post_id ); if ( $parent_post->post_status !== 'publish' || get_post_meta( $parent_post_id, '_custom_stock_saved', true ) ) { return; } // 获取产品对象 $product = wc_get_product( $parent_post_id ); if ( ! $product ) { return; } // 写入主产品库存数据 $main_stock = $product->get_stock_quantity(); $wpdb->insert( 'wp_woocommerce_stock_custom', [ 'post_id' => $parent_post_id, 'user_id' => $user_id, 'stock_quantity' => $main_stock ? $main_stock : 0, 'log_date' => current_time( 'Y-m-d' ) ] ); // 可变产品额外遍历写入所有变体库存 if ( $product->is_type( 'variable' ) ) { $variations = $product->get_children(); foreach ( $variations as $variation_id ) { $variation_obj = wc_get_product( $variation_id ); $variation_stock = $variation_obj->get_stock_quantity(); $wpdb->insert( 'wp_woocommerce_stock_custom', [ 'post_id' => $variation_id, 'user_id' => $user_id, 'stock_quantity' => $variation_stock ? $variation_stock : 0, 'log_date' => current_time( 'Y-m-d' ) ] ); } } // 标记已写入,避免同个产品重复插入数据 update_post_meta( $parent_post_id, '_custom_stock_saved', 'yes' ); }
注意事项
- 代码中使用WooCommerce原生方法获取库存,兼容性优于直接读取post_meta
- 自动兼容简单产品、可变产品两种场景,可变产品会自动遍历所有变体存储对应数据
- 如果你的数据库表前缀不是默认的
wp_,需要修改wp_woocommerce_stock_custom为你实际的表名 - 不需要限制首次发布写入的话,删除对应判断代码即可,可支持每次库存变动都写入记录
内容的提问来源于stack exchange,提问作者Siddharth
相关产品推荐
相关产品推荐

