首页 > 解决方案 > 登录用户的 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

方案 2

Woocommerce 使用上面的代码段,而是为登录用户计算销售价格的 10% 折扣,返回:

方案 1

方案 2

我该如何解决?谢谢你的帮助

标签: phpwordpresswoocommercepricediscount

解决方案


自 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 文件中。测试和工作。


推荐阅读