使用PHP程序动态修改 WordPress 价格实现会员优惠等功能

开发电子商务网站的时候,我们经常需要对会员设置一定的优惠,比如,会员打八折,WooCommerce没有为我们提供根据会员类型动态价格的能力,想要实现这个功能,我们可以使用插件,或者自己写一些代码。

想要实现这个功能,我们只要需要做到两点:修改会员浏览商品时的商品价格、修改会员购物车中和结账时的商品价格。

修改WooCommerce商品显示价格 #

下面的代码实现了用户登录网站后,商品价格统一打8折显示的功能。


add_filter( 'woocommerce_get_price_html', function ( $price_html, $product ) {

    // 只在前端修改
    if ( is_admin() ) return $price_html;

    // 只在设置了商品价格时才修改,免费产品直接返回
    if ( '' === $product->get_price() ) return $price_html;

    // 如果用户登录,打八折  
    if ( wc_current_user_has_role( 'customer' ) ) {
        $orig_price = wc_get_price_to_display( $product );
        $price_html = wc_price( $orig_price * 0.80 );
    }

    return $price_html;

}, 9999, 2 );

修改购物车中的商品价格 #

下面的代码实现了会员登录后,修改购物车中的产品价格的功能。用户添加好商品去结账时,订单价格会按照购物车中显示的商品价格计算。


add_action( 'woocommerce_before_calculate_totals', function ( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    // 如果客户没有登录,不显示价格
    if ( ! wc_current_user_has_role( 'customer' ) ) return;

    // 遍历购物车项目,每个项目都打八折
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
        $price = $product->get_price();
        $cart_item['data']->set_price( $price * 0.80 );
    }

}, 9999 );

因为本文中所描述需求的逻辑非常简单,使用代码实现就显得非常简洁,如果您有更复杂的动态价格需求,使用本文中介绍的方法理论上也可以实现,但是可能要多写很多代码,这种情况下,建议使用插件来管理动态价格,比如?Dynamic Pricing?或?Advanced Dynamic Pricing for WooCommerce