php 修改 wordpress,使用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 forWooCommerce。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值