Last active
October 16, 2024 03:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Check for one or many WooCommerce Subscriptions by SKU | |
* | |
* @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 | |
} | |
$subscriptions = wcs_get_users_active_subscriptions( $user_id ); | |
if( empty( $subscriptions ) ){ | |
return false; // No subscriptions | |
} | |
if( $sku_list === NULL ){ | |
return true; // Early return if no SKUs to check | |
} | |
if( ! is_array( $sku_list ) ){ | |
$sku_list = [ $sku_list ]; | |
} | |
foreach( $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; | |
} | |
function register_is_subscriber() { | |
// As best as I understand, this allows global use of this function | |
} | |
add_action( 'init', 'register_is_subscriber' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment