为当前活跃的WooCommerce订阅用户提供全站折扣



我正在运行一个有cookie订阅业务的网站。如果客户已经是一个活跃的订阅者,我希望任何额外购买的产品都是半价(因为它们是一起发货的)。最好的方法是什么?

我有这个函数来标识活动订阅者状态:

function has_active_subscription( $user_id=null ) {
// When a $user_id is not specified, get the current user Id
if( null == $user_id && is_user_logged_in() ) 
$user_id = get_current_user_id();
// User not logged in we return false
if( $user_id == 0 ) 
return false;
global $wpdb;
// Get all active subscriptions count for a user ID
$count_subscriptions = $wpdb->get_var( "
SELECT count(p.ID)
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm 
ON p.ID = pm.post_id
WHERE p.post_type = 'shop_subscription' 
AND p.post_status = 'wc-active'
AND pm.meta_key = '_customer_user' 
AND pm.meta_value > 0
AND pm.meta_value = '$user_id'
" );
return $count_subscriptions == 0 ? false : true;
}

我试着拨打优惠券代码,但没有任何运气。我是新手。

要实现活跃订阅者购买的额外产品的半价折扣,您可以使用WooCommerce过滤器钩子在产品添加到购物车之前修改产品价格:

add_filter( 'woocommerce_product_get_price', 'apply_half_price_for_active_subscribers', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'apply_half_price_for_active_subscribers', 10, 2 );
function apply_half_price_for_active_subscribers( $price, $product ) {
if ( has_active_subscription() && WC()->cart->cart_contents_count > 0 ) {
// Get the total quantity of products in the cart for the current user
$user_id = get_current_user_id();
$product_count = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['data']->get_id() != $product->get_id() && $cart_item['data']->is_purchasable() ) {
$product_user_id = $cart_item['data']->get_meta( '_customer_user', true );
if ( empty( $product_user_id ) || $product_user_id == $user_id ) {
$product_count += $cart_item['quantity'];
}
}
}
// Apply half price discount for additional products purchased
if ( $product_count > 0 ) {
$price = $price / 2;
}
}
return $price;
}

相关内容

  • 没有找到相关文章

最新更新