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

WooCommerce实现每完成一笔订单后所有商品涨价20美元

在WooCommerce中实现每完成一笔订单后所有商品涨价20美元

实现逻辑

监听WooCommerce的订单完成状态钩子,每次订单标记为「已完成」时,遍历所有商品并将其常规价格上调20美元。

代码实现

将以下代码添加到主题functions.php文件或自定义插件中:

/**
 * 订单完成后上调所有商品价格20美元
 */
add_action('woocommerce_order_status_completed', 'increase_all_products_price_on_order_complete');
function increase_all_products_price_on_order_complete($order_id) {
    // 定义每次涨价金额(美元)
    $price_increment = 20;

    // 获取所有已发布的产品
    $products = get_posts(array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'numberposts' => -1,
        'fields' => 'ids'
    ));

    foreach ($products as $product_id) {
        $product = wc_get_product($product_id);
        
        // 跳过无法编辑价格的产品类型
        if (!$product || !in_array($product->get_type(), array('simple', 'variable'))) {
            continue;
        }

        // 更新简单产品价格
        if ($product->is_type('simple')) {
            $current_price = (float)$product->get_regular_price();
            $new_price = $current_price + $price_increment;
            $product->set_regular_price($new_price);
            $product->save();
        }

        // 更新可变产品的所有变体价格
        if ($product->is_type('variable')) {
            foreach ($product->get_available_variations() as $variation_data) {
                $variation = wc_get_product($variation_data['variation_id']);
                $current_price = (float)$variation->get_regular_price();
                $new_price = $current_price + $price_increment;
                $variation->set_regular_price($new_price);
                $variation->save();
            }
        }
    }
}

注意事项

  • 测试先行:先在测试环境验证功能,避免影响线上店铺运营。
  • 数据备份:操作前备份产品数据,防止价格错误无法回滚。
  • 重复触发防护:确保仅在订单状态变为「已完成」时执行,避免状态反复切换导致多次涨价。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:31:00