Several times I have met YITH WooCommerce Subscription plugin during website development. And sometimes I had to check the Subscription status or membership for the WordPress user before allowing some actions on the website. Actually, this is a very basic action, but there was very little information on how to implement this functionality. So, I decided to write a little note, mainly for myself. But someone else may find it useful too.

It was not difficult to discover that the YITH WooCommerce Subscription plugin keeps its data as a post of “ywsbs_subscription” type. So, we can use get_posts() function to request the status of the subscription and check that subscription has not yet expired.

Here is the function that checks the subscription:

/**
 *  Rerurns the status of the product subscription for user.
 */
function CheckStatus($product_id, $user_id) {
  $subscriptions = get_posts([ 
    "numberposts" => -1,
    "post_type" => "ywsbs_subscription", // Subscription post type
    "orderby" => "post_date", 
    "order" => "ASC",
    "meta_query" => [ // Meta query
	[
	  "key" => "product_id", // Product ID
	  "value" => $product_id,
	  "compare" => "=",
	],
	[
	  "key" => "user_id", // User ID
	  "value" => $user_id,
	  "compare" => "=",
	],
	[
	  "key" => "start_date", // Subscription start date filter
	  "value" => time(),
	  "compare" => "<",
	],
	[
	  "key" => "payment_due_date", // Subscription due date filter
	  "value" => time(),
	  "compare" => ">",
	],
	[
	  "key" => "status", // Subscription status filter
	  "value" => "active", 
	  "compare" => "=",
	],
    ]
  ]);
		
  if(count($subscriptions)>0){
    // Active subscription found
    return ["status"=>"active", "product_id"=>$product_id, "product_name"=>get_post_meta($subscriptions[0]->ID, "product_name",true)];
  }else{
    // No active subscription found
    return  ["status"=>"expired", "product_id"=>$product_id];
  }
} 
How to check active subscription using YITH WooCommerce Subscription?