共计 1199 个字符,预计需要花费 3 分钟才能阅读完成。
开发电子商务网站的时候,咱们常常须要对会员设置肯定的优惠,比方,会员打八折,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。
正文完