php - 在 Woocommerce 3 中以编程方式在全球范围内更改产品类别的产品价格
问题描述
是否可以在 Woocommerce 中更改特定产品类别中所有产品的价格?
例如,如果我想将“衬衫”产品类别中的所有产品价格更改为 50,可以吗?
任何帮助将不胜感激。
解决方案
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或术语名称。
推荐阅读
- git - 如何获取 Libre Office Writer 保存的文件的有用 git diff,并在命令行中输出?
- julia - 在 Julia 中,数组访问的循环很慢
- swift - 正则表达式以防止重复的字符或数字
- javascript - 愿望清单按钮仅在强制页面刷新时有效,在选择日历日期时无效
- docker - 为什么我不能在 Dockerfile 中打印带有 echo 的 ARG?
- r - 如何将数据从 SparkR 插入到 hadoop 集群中的 Hbase
- jquery - 如何在 JSP 中查找开始和结束正文标记
- c# - 在运行时更改 winforms 控件
- python - 给定python中的距离计算网格值
- sql - 查询以获取列名和值