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

WooCommerce+WFCM插件:同步同名商品价格的代码问题求助

解决WooCommerce同步同名商品价格的问题

先看修正后的可运行代码:

add_action('save_post', 'update_prices_by_product_name', 10, 2);

function update_prices_by_product_name($post_id, $post) {
    // 排除自动保存、修订版,以及非产品类型的内容
    if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id) || $post->post_type !== 'product') {
        return;
    }

    // 获取当前商品的名称和价格
    $product_name = $post->post_title;
    $product = wc_get_product($post_id);
    $new_regular_price = $product->get_regular_price();
    $new_sale_price = $product->get_sale_price(); // 如果需要同步促销价可以保留,否则删除

    // 精确查询同名商品(排除当前商品)
    $args = array(
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'post__not_in'   => array($post_id),
    );

    $query = new WP_Query($args);
    // 添加精确匹配标题的条件
    add_filter('posts_where', function($where) use ($product_name) {
        global $wpdb;
        $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_title = %s", $product_name);
        return $where;
    });

    $related_products = $query->get_posts();
    remove_filter('posts_where', '__return_empty_string'); // 移除钩子避免影响其他查询

    // 避免无限循环,先移除当前钩子
    remove_action('save_post', 'update_prices_by_product_name', 10);

    foreach ($related_products as $related_product) {
        $related_product_id = $related_product->ID;
        
        // 更新常规价格
        update_post_meta($related_product_id, '_regular_price', $new_regular_price);
        // 更新显示价格(WooCommerce需要这个字段同步)
        update_post_meta($related_product_id, '_price', $new_regular_price);
        
        // 如果需要同步促销价,取消下面注释
        // if (!empty($new_sale_price)) {
        //     update_post_meta($related_product_id, '_sale_price', $new_sale_price);
        // } else {
        //     delete_post_meta($related_product_id, '_sale_price');
        // }

        // 刷新产品缓存,确保价格立即生效
        wc_delete_product_transients($related_product_id);
    }

    // 重新添加钩子
    add_action('save_post', 'update_prices_by_product_name', 10, 2);
}

原代码的问题分析

  1. 查询条件无效:get_posts不支持直接传入post_title作为筛选条件,原代码的'post_title' => $product_name完全不起作用,导致查询出所有商品。
  2. 未处理价格同步:原代码仅更新商品标题,完全没有修改价格相关的元字段,根本实现不了价格同步的需求。
  3. 未过滤无效触发:save_post钩子会在自动保存草稿、保存修订版时触发,会导致不必要的重复执行甚至错误。
  4. 无限循环风险:更新商品时会再次触发save_post,原代码没有处理这个问题,可能导致死循环。

修正后的关键改进

  • 加入自动保存、修订版的判断,只在正式发布/更新商品时执行。
  • 使用WP_Query配合posts_where钩子实现精确匹配商品标题的查询,确保只找到同名商品。
  • 同步更新_regular_price和_price两个核心价格字段(WooCommerce依赖这两个字段显示价格),可选同步促销价。
  • 更新前移除save_post钩子,更新后重新添加,避免无限循环。
  • 调用wc_delete_product_transients刷新产品缓存,确保修改后的价格立即在前台生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:45:01