php - 登录用户的 WooCommerce 产品定制折扣价
问题描述
我有一个关于在 WooCommerce 中管理价格的问题。
我有一家只卖简单产品的商店。假设对于所有订阅者和客户,每种产品的正常价格折扣 10%。这很容易:
function custom_price( $price, $product ) {
global $post, $blog_id;
$post_id = $post->ID;
get_post_meta($post->ID, '_regular_price');
if ( is_user_logged_in() ) {
return $price = ($price * 0.9);
} else{
return $price;
}
}
add_filter( 'woocommerce_get_price', 'custom_price', 10, 2);
对于已经有促销价的产品,我希望 woocommerce 以正常价格计算登录用户的折扣,并且客户可以看到促销价和折扣价之间的最低价格。所以:
方案 1
- 正常价格:100
- 登录用户专用价格:90(原价 10% 折扣)
- 产品售价:85
- 登录用户的价格必须是:85
方案 2
- 正常价格:100
- 登录用户专用价格:90(原价 10% 折扣)
- 产品售价:95
- 登录用户的价格必须是:90
Woocommerce 使用上面的代码段,而是为登录用户计算销售价格的 10% 折扣,返回:
方案 1
- 登录用户的产品价格:76.5(促销价 10% 折扣,85)
方案 2
- 登录用户的产品价格:85.5(促销价 10% 折扣,95)
我该如何解决?谢谢你的帮助
解决方案
自 WooCommerce 3 以来,您的问题代码已过时且已弃用……而是使用以下应符合您的场景的代码:
add_filter( 'woocommerce_product_get_price', 'custom_discount_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'custom_discount_price', 10, 2 );
function custom_discount_price( $price, $product ) {
// For logged in users
if ( is_user_logged_in() ) {
$discount_rate = 0.9; // 10% of discount
// Product is on sale
if ( $product->is_on_sale() ) {
// return the smallest price value between on sale price and custom discounted price
return min( $price, ( $product->get_regular_price() * $discount_rate ) );
}
// Product is not on sale
else {
// Returns the custom discounted price
return $price * $discount_rate;
}
}
return $price;
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。测试和工作。
推荐阅读
- wordpress - 为什么 Facebook 无法抓取我的页面?
- c# - 无法调试到 System.ServiceModel v 4.8.3825.0 的参考源
- python - 如何使用现有字典的名称创建新字典?
- java - 即使在语句回滚之后,Derby DB 也会增加 ID
- postgresql - 无法在 postgres 中创建模式
- ajax - 如何广播一个可以为每个用户专门定制的 laravel 事件
- asp.net - InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“UltraTel.Models.ViewModels.FRMultiViewModel”
- php - 不存在的 .htaccess 文件
- django - Django save 方法正在覆盖字段值
- c# - 在 .net core razor 页面中使用远程属性。返回页面时数据丢失