对于 WooCommerce 订阅,我没有找到任何功能来检查当前用户是否有活动订阅。
所以我做了这个答案,它仍然适用于 WooCommerce 3+ 和最后一个 WC 订阅插件:检测当前用户是否有活动订阅
因此,使用 woocommerce_add_to_cart 动作钩子中的自定义函数并使用我的旧答案中的条件函数代码,你会得到它的工作:
// Conditional function detecting if the current user has an active subscription
function has_active_subscription( $user_id=null ) {
// if the user_id is not set in function argument we get the current user ID
if( null == $user_id )
$user_id = get_current_user_id();
// Get all active subscrptions for a user ID
$active_subscriptions = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'post_type' => 'shop_subscription', // Subscription post type
'post_status' => 'wc-active', // Active subscription
) );
// if user has an active subscription
if(!empty($active_subscriptions)) return true;
else return false;
}
// Conditionally checking and adding your subscription when a product is added to cart
add_action( 'woocommerce_add_to_cart', 'add_subscription_to_cart', 10, 6 );
function add_subscription_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// Here define your subscription product
$subscription_id = 2282;
$found = false;
if ( is_admin() || has_active_subscription() || $product_id == $subscription_id ) return; // exit
// Checking if subscription is already in cart
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['product_id'] == $subscription_id ){
$found = true;
break;
}
}
// if subscription is not found, we add it
if ( ! $found )
WC()->cart->add_to_cart( $subscription_id );
}
代码放在任何插件 php 文件中(钩子可以在活动主题的 function.php 文件中使用)。
代码经过测试并且可以工作。
如果订阅从购物车中删除,我们将在结帐时重新签入:
add_action( 'woocommerce_before_checkout_form', 'check_subscription_in_checkout', 10, 0 );
function check_subscription_in_checkout() {
// Here define your subscription product
$subscription_id = 2282;
$found = false;
if ( is_admin() || has_active_subscription() || ! is_checkout() ) return; // exit
// Checking if subscription is already in cart
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['product_id'] == $subscription_id ){
$found = true;
break;
}
}
// if subscription is not found, we add it
if ( ! $found )
WC()->cart->add_to_cart( $subscription_id );
}