You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用WP All Import阻止带special标签的商品更新价格

WP All Import阻止带「special」标签商品更新价格的解决方案

你当前使用的woocommerce_product_set_price钩子无法生效,是因为WP All Import更新商品价格时,通常直接操作数据库元字段,不会触发这个WooCommerce钩子。以下是两种适配的解决方法:

方法一:利用WP All Import专属钩子拦截

通过wp_all_import_post_saved钩子在商品更新后恢复原始价格,需要先在导入模板中备份原始价格:

function revert_special_product_price_after_import( $post_id, $xml_node, $is_update ) {
    // 仅处理商品更新操作,新增商品不干预
    if ( !$is_update ) return;

    // 检查商品是否带有"special"标签
    if ( has_term( 'special', 'product_tag', $post_id ) ) {
        $product = wc_get_product( $post_id );
        if ( !$product ) return;

        // 读取提前备份的原始价格(需在导入模板中设置)
        $original_price = get_post_meta( $post_id, '_wp_backup_regular_price', true );
        
        if ( $original_price ) {
            // 恢复原始价格
            $product->set_regular_price( $original_price );
            $product->save();
            // 可选:记录操作日志
            error_log( "商品ID {$post_id} 因含special标签,已恢复原始价格" );
        }
    }
}
add_action( 'wp_all_import_post_saved', 'revert_special_product_price_after_import', 10, 3 );

配套设置步骤:

在WP All Import的导入映射界面,添加一个自定义字段_wp_backup_regular_price,将其映射到商品导入前的常规价格(即当前店铺内的价格,而非XML中的新价格)。

方法二:通过WooCommerce导入前置钩子拦截

如果WP All Import兼容WooCommerce原生导入逻辑,可使用woocommerce_product_import_pre_save_product_object钩子在商品保存前强制保留原价格:

function lock_special_product_price_during_import( $product, $import_data ) {
    // 检查商品是否带有"special"标签
    if ( has_term( 'special', 'product_tag', $product->get_id() ) ) {
        // 用原始价格覆盖导入的新价格
        $original_price = $product->get_regular_price();
        $product->set_regular_price( $original_price );
    }
    return $product;
}
add_filter( 'woocommerce_product_import_pre_save_product_object', 'lock_special_product_price_during_import', 10, 2 );

原代码失效原因

woocommerce_product_set_price仅在调用$product->set_price()方法时触发,但WP All Import为提升导入效率,通常直接更新_regular_price等元字段,不会调用该方法,因此你的钩子无法拦截价格修改。

内容的提问来源于stack exchange,提问作者Costas Saloubardos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 13:15:16