登录用户的 WooCommerce 产品自定义折扣价 [英] WooCommerce product custom discounted price for logged in users

查看:28
本文介绍了登录用户的 WooCommerce 产品自定义折扣价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在 WooCommerce 中管理价格的问题.

I have a question about managing prices in WooCommerce.

我有一家只卖简单产品的商店.假设对于所有订阅者和客户,每种产品的正常价格都打了 10% 的折扣.这很简单:

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);

对于已经有促销价的产品,我希望 woocommerce 为登录用户计算正常价格的折扣,并且客户可以看到促销价和折扣价之间的最低价格.因此:

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:

场景一

  • 正常价格:100
  • 专为登录用户提供的价格:90(比正常价格优惠 10%)
  • 产品售价:85
  • 登录用户的价格必须是:85

场景 2

  • 正常价格:100
  • 专为登录用户提供的价格:90(比正常价格优惠 10%)
  • 产品售价:95
  • 登录用户的价格必须是:90

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

Woocommerce, with the snippet above, instead calculates the 10% discount for logged in users on the sale price, returning:

场景一

  • 登录用户的产品价格:76.5(85 折优惠 10%)

场景 2

  • 登录用户的产品价格:85.5(95 折优惠 10%)

我该如何解决?感谢您的帮助

How can I solve it? Thanks for your help

推荐答案

自 WooCommerce 3 以来,您的问题代码已过时且已弃用……而是使用以下应符合您方案的代码:

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;
}

代码位于活动子主题(或活动主题)的 functions.php 文件中.经测试有效.

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

这篇关于登录用户的 WooCommerce 产品自定义折扣价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆