WooCommerce Subscription

add_filter('woocommerce_add_to_cart_validation', 'check_num_of_subscriptions', 10, 2);

function check_num_of_subscriptions($valid, $product_id)
{
    $product_to_add = wc_get_product($product_id);
    
    if ($product_to_add instanceof WC_Product_Subscription || $product_to_add instanceof WC_Product_Variable_Subscription) {
        
        // alternative use: $has_sub = wcs_user_has_subscription( '', '', 'active' );
        if (has_active_subscription()) {
            // cart validation must fail, because user is not allowed to have multiple subscriptions
            return false;
        } else {
            return true;
        }
    }
    return $valid;
}

function has_active_subscription()
{
    
    $user_id = get_current_user_id();
    
    $active_subscriptions = get_posts(array(
        'numberposts' => -1,
        'meta_key' => '_customer_user',
        'meta_value' => $user_id,
        'post_type' => 'shop_subscription',
        'post_status' => 'wc-active'
        
    ));
    if (!empty($active_subscriptions))
        return true;
    else
        return false;
}

How To Detect User Subscriptions WooCommerce?

robinhenniges.com/blog/woocommerce-subscription-allow-only-one-active-subscription

Conditional Statement to Detect if a User has a Subscription with Woocommerce Subscriptions | ClickNathan – Handmade Websites

/**
 * Check if the current user has an active subscription.
 * Redirect the user if no active subscription and the current post is a singule forum.
 * This code should not be copied and pasted as is. It is only to demonstrate the wcs_user_has_subscription() function.
 *
 * wcs_user_has_subscription( $user_id = 0, $product_id = '', $status = 'any' )
 * @param int (optional) The ID of a user in the store. If left empty, the current user's ID will be used.
 * @param int (optional) The ID of a product in the store. If left empty, the function will see if the user has any subscription.
 * @param string (optional) A valid subscription status. If left empty, the function will see if the user has a subscription of any status.
 */
add_action( 'template_redirect', 'ultimatewoo_check_user_subscriptions' );
function ultimatewoo_check_user_subscriptions() {
	$has_sub = wcs_user_has_subscription( '', '', 'active' );
	if ( ! $has_sub && is_singular( 'forum' ) ) {
		wp_redirect( get_permalink( 2626 ) );
		exit;
	}
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert