我只是想知道是否有人能解决我目前的问题。实际上,我正试图在购物车上为正在访问我的网上商店的用户打印一个定制价格。以下是我计划设定的条件。
没有登录->的用户没有折扣,不应该在我的购物车页面上看到定制价格显示。
作为“客户”用户角色登录的用户->没有折扣,不应该在我的购物车页面上看到定制定价显示。
以"paid_customer“用户角色->折扣登录的用户,假设在我的购物车页面上看到定制定价显示。
目前,只有未登录的用户和"paid_customer“用户角色的定价显示正常工作,而不是为”客户“角色。不确定这里是否正确地识别了客户角色。
下面是用于此条件的钩子:
add_filter( 'woocommerce_cart_item_price', function ( $price, $values, $cart_item_key ){
global $woocommerce;
$items = $woocommerce->cart->get_cart();
$user = wp_get_current_user();
if (!is_user_logged_in() || (in_array( 'customer', (array) $user->roles ))){
return $price;
}else{
foreach($items as $item => $values) {
echo "Discounted Price : " . get_post_meta($values['product_id'] , ('_sale_price', true);
return $price;
}
}
}, 10, 3);编辑:
我的价格折扣已经管理WooCommerce的高级动态定价插件,根据我的自定义用户角色,所以我不需要担心价格输出了。
请参阅下面基于@LoicTheAztec接受答案的代码答案。
发布于 2020-07-07 10:16:14
您应该在问题中提到您正在使用的插件,因为StackOverFlow上的问题/答案是针对洞社区的,而不仅仅是针对您的。
您的代码有一些错误,可以简化:
add_filter( 'woocommerce_cart_item_price', 'filter_wc_cart_item_price', 10, 3 );
function filter_wc_cart_item_price( $price, $values, $cart_item_key ){
// For 'paid_customer' user role when sale price is defined
if ( current_user_can( 'paid_customer' ) && $sale_price = get_post_meta( $values['product_id'],'_sale_price', true) ) {
// The custom formatted sale price
$price = sprintf( __("Discounted Price : %s"), wc_price( $sale_price ) );
}
return $price;
}应该管用的。
对回答代码的编辑是不正确的,因为过滤器钩子中的数据总是需要返回,但不回显:
add_filter( 'woocommerce_cart_item_price', 'filter_wc_cart_item_price', 10, 3 );
function filter_wc_cart_item_price( $price, $values, $cart_item_key ){
// For 'lifetime_member' user role when sale price is defined
if ( current_user_can( 'paid_customer' ) )
{
$price = __("Members Price (5% Off): ") . $price;
}
elseif ( current_user_can('customer') )
{
$price = __("Normal Price: ") . $price;
}
return $price;
}这是正确的工作方式。
发布于 2020-07-07 06:13:00
用这个钩子代替"woocommerce_before_calculate_totals“
add_action("woocommerce_before_calculate_totals", "set_product_price");
function set_product_price($cart_obj) {
$user = wp_get_current_user();
foreach ($cart_obj->get_cart() as $item) {
if (!is_user_logged_in() || (in_array( 'customer', (array) $user->roles ))){
$item['data']->set_price(20);
} else {
$item['data']->set_price(15);
}
}
}这样,您就不需要在结帐和订货过程中处理价格了。
发布于 2020-07-07 12:14:19
这就是我为实现我想要的而做的事情(感谢@LoicTheAztec的回答)
add_filter( 'woocommerce_cart_item_price', 'filter_wc_cart_item_price', 10, 3 );
function filter_wc_cart_item_price( $price, $values, $cart_item_key ){
// For 'lifetime_member' user role when sale price is defined
if ( current_user_can( 'paid_customer' )) {
echo "Members Price (5% Off): ";
} elseif (current_user_can('customer')){
echo "Normal Price: ";
}
return $price;
}我的价格折扣已经管理WooCommerce的高级动态定价插件,根据我的自定义用户角色,所以我不需要担心价格输出了。
https://stackoverflow.com/questions/62768594
复制相似问题