Skip to content

Instantly share code, notes, and snippets.

@ara303
Last active September 8, 2024 02:57
Show Gist options
  • Save ara303/264409573025ba8d3b987db673245fcf to your computer and use it in GitHub Desktop.
Save ara303/264409573025ba8d3b987db673245fcf to your computer and use it in GitHub Desktop.
WooCommerce Subscriptions check if the logged-in user has any or given subscription tiers
/**
* To use, initialise this in your theme's functions.php or a plugin file. Then, in a theme file:
*
* if( is_subscriber() ){
* echo "You subscribe to any product.";
* } else if( is_subscriber( 'subscription_sku' ){
* echo "You subscribe to the `subscription_sku` product.";
* } else {
* echo "No subscriptions found.";
* }
*/
<?php
/**
* Check if the current user has an active WooCommerce Subscription
*
* @param string|array $sku_list Optional. Single SKU as string or array of SKUs to check against.
* @return bool True if the user has an active subscription (matching the SKU(s) if provided), false otherwise
*/
function is_subscriber( $sku_list = null ){
$user_id = get_current_user_id();
if ( ! $user_id ){
return false; // Not logged in, constitutes a fail condition
}
$active_subscriptions = wcs_get_users_active_subscriptions( $user_id );
if ( empty( $active_subscriptions ) ){
return false; // Returns an array which if empty means no active subscriptions
}
if ( $sku_list === NULL ){
return true; // If no params given for `is_subscriber()`, it can't matter what type they have and let them in
}
if ( ! is_array( $sku_list ) ) {
$sku_list = array( $sku_list ); // If one param is given, array-ify it for the below
}
foreach ( $active_subscriptions as $subscription ){
foreach ( $subscription->get_items() as $item ){
$product = $item->get_product();
if ( $product && in_array( $product->get_sku(), $sku_list ) ){
return true; // If the params' array include an SKU, we grant access
}
}
}
return false; // Last-ditch; don't give access if somehow everything earlier failed
}
function register_is_subscriber() {
// This instantiates is_subscriber globally.
}
add_action( 'init', 'register_is_subscriber' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment