php - 用户角色的 Woocommerce 折扣
问题描述
编辑:如你所见,我是新来的。很抱歉让您头疼这是目前的问题:代码现在正在运行!但是,当商店页面上的产品价格与购物车和结帐页面不同时,这可能与税收有关。
为了清楚起见,我已插入不含增值税的价格,并且在商店页面上不含增值税。但在购物车页面上计算增值税。
概括:
- 产品价格为:10 欧元</li>
- 折扣 22% 为 7.80 欧元</li>
- 含 24% 的增值税:~ 9.67 欧元</li>
- 但在购物车和结帐页面上显示总计:11.16 欧元</li>
我目前正在使用 Wordpress + Woocommerce 进行一个非常复杂的项目,并且我对 PHP 和 Wordpress/Woocommerce 钩子不太熟悉。我正在尝试对 X 类产品应用百分比折扣。我遇到了类似的问题
遇到非数值
在仪表板上,价格与购物车/结帐页面上的产品存档页面不同。
这是我在functions.php上的代码:
add_filter('woocommerce_product_variation_get_price', 'custom_price', 10, 2);
add_filter('woocommerce_product_get_price', 'custom_price', 10, 2);
add_filter('woocommerce_get_price', 'custom_price', 10, 2);
function custom_price($price, $product)
{
if (!is_user_logged_in()) return $price;
if (has_role('hintaluokka-5')) {
$price = $price * 0.95;
} elseif (has_role('hintaluokka-12')) {
$price = $price * 0.88;
} elseif (has_role('hintaluokka-15')) {
$price = $price * 0.85;
} elseif (has_role('hintaluokka-22')) {
if (has_term('kastikkeet', 'product_cat', $product->ID)) {
$price = $price * 0.78;
} else {
$price = $price * 0.9;
}
}
return $price;
}
function has_role($role = '', $user_id = null)
{
if (is_numeric($user_id))
$user = get_user_by('id', $user_id);
else
$user = wp_get_current_user();
if (empty($user))
return false;
return in_array($role, (array) $user->roles);
}
解决方案
试试这个代码:
add_filter( 'woocommerce_product_variation_get_price', 'custom_price', 10, 2 );
add_filter( 'woocommerce_product_get_price', 'custom_price', 10, 2 );
function custom_price( $price, $product ) {
if ( ! is_user_logged_in() ) {
return $price;
}
if ( has_role( 'hintaluokka-5' ) ) {
$price *= 0.95;
} elseif ( has_role( 'hintaluokka-12' ) ) {
$price *= 0.88;
} elseif ( has_role( 'hintaluokka-15' ) ) {
$price *= 0.85;
} elseif ( has_role( 'hintaluokka-22' ) ) {
if ( has_term( 'kastikkeet', 'product_cat', $product->ID ) ) {
$price *= 0.78;
} else {
$price *= 0.9;
}
}
return $price;
}
function has_role( $role = '', $user_id = null ) {
if ( is_numeric( $user_id ) ) {
$user = get_user_by( 'id', $user_id );
} else {
$user = wp_get_current_user();
}
if ( empty( $user ) ) {
return false;
}
return in_array( $role, $user->roles, true );
}
我认为这里没有什么大问题。只有一个钩子不再使用(已弃用)。
如果这没有帮助,请发布错误消息。
推荐阅读
- mongodb - 在 mongodb 聚合中使用 $match 后如何包含一个空数组
- android - (问) Android Studio北极狐(2020.3.1)中没有方法签名
- c++ - 如何显示地图的 k 最少和最多元素?
- python - 意外错误“数据包太大”,关闭连接 socketio flask
- python - 如何裁剪 fit.gz 文件,然后使用 Python 查看裁剪后的图像?
- extjs - 清除 ExtJS 应用程序中的缓存
- api - 使用具有令牌的 auth 使用 jmeter 进行性能测试
- python - 为什么当给定种群规模的代数增加时,超体积会减少?
- visual-studio-code - VS Code 终端中的 ESLint 不会像在编辑器中那样检测类型保护
- r - 使用 grid.arrange 显示多个格子图(来自格子)