首页 > 解决方案 > 在 Woocommerce 3 中以编程方式在全球范围内更改产品类别的产品价格

问题描述

是否可以在 Woocommerce 中更改特定产品类别中所有产品的价格?

例如,如果我想将“衬衫”产品类别中的所有产品价格更改为 50,可以吗?

任何帮助将不胜感激。

标签: phpwordpresswoocommercecustom-taxonomyprice

解决方案


50 要更改整个产品类别 的固定金额的产品价格shirts

// Simple, grouped and external products
add_filter('woocommerce_product_get_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_get_regular_price', 'conditional_custom_price', 99, 2 );
// Variable
add_filter('woocommerce_product_variation_get_regular_price', 'conditional_custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'conditional_custom_price', 99, 2 );
function conditional_custom_price( $price, $product ) {
    if( has_term( 'shirts', 'product_cat', $product->get_id() ) ){
        // Delete product cached price  (if needed uncomment it)
        // wc_delete_product_transients($product->get_id());

        $price = 50; // X2 for testing
    }
    return $price;
}

// Variations
add_filter('woocommerce_variation_prices_price', 'conditional_custom_variation_price', 99, 3 );
add_filter('woocommerce_variation_prices_regular_price', 'conditional_custom_variation_price', 99, 3 );
function conditional_custom_variation_price( $price, $variation, $product ) {
    if( has_term( 'shirts', 'product_cat', $product->get_id() ) ){
        // Delete product cached price  (if needed uncomment below)
        // wc_delete_product_transients($variation->get_id());

        $price = 50;
    }
    return $price;
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

基于此答案:通过 WooCommerce 3 中的挂钩更改产品价格

它处理所有类型的 Woocommerce 产品类型。条件 Wordpress 函数has_term()可以处理关于任何产品类别的术语 Id术语 slug术语名称。


推荐阅读