问题
I have a question about managing prices in WooCommerce.
I have a store only with simple products. Let's say that for all subscribers and customers the regular price of each product is discounted by 10%. This was easy:
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);
For products that already have a sale price, I would like woocommerce to calculate the discount for logged in users on the regular price, and that the customer could see the lowest price between the sale price and the discounted price. Therefore:
Scenario 1
- Regular price: 100
- Price dedicated to logged in users: 90 (10% off on regular price)
- Product sale price: 85
- The price for logged in user must be: 85
Scenario 2
- Regular price: 100
- Price dedicated to logged in users: 90 (10% off on regular price)
- Product sale price: 95
- The price for logged in user must be: 90
Woocommerce, with the snippet above, instead calculates the 10% discount for logged in users on the sale price, returning:
Scenario 1
- product price for logged in users: 76.5 (10% off on the sale price, 85)
Scenario 2
- product price for logged in users: 85.5 (10% off on the sale price, 95)
How can I solve it? Thanks for your help
回答1:
Your question code is outdated and deprecated since WooCommerce 3… Instead use the following that should match your scenario:
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;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
来源:https://stackoverflow.com/questions/62973744/woocommerce-product-custom-discounted-price-for-logged-in-users