A Cozmoslabs Product
Documentation / Developer Knowledge Base / Exclude products created by expired members from WooCommerce queries

Exclude products created by expired members from WooCommerce queries

If you have a website where your users are allowed to setup their own shop and create products (using WC Vendors, WC Marketplace or something similar) you can use Paid Member Subscriptions to sell access rights to these vendors.

Using the code from below, you can exclude from the Shop page (or product category archive) products created by users that have an expired membership:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function pmsc_check_subscription( $user_id ) {
	if (empty($user_id)) return false;
 
	global $wpdb;
 
	$sql = $wpdb->prepare('SELECT user_id, subscription_plan_id, expiration_date, status FROM '.$wpdb->prefix.'pms_member_subscriptions WHERE user_id = %d', $user_id);
	$rows = $wpdb->get_results($sql, ARRAY_A);
	$member_subscriptions = array();
 
	if (!empty($rows)) {
		foreach ($rows as $subscription) {
			if (!empty($subscription['status']) && ($subscription['status'] == 'active' || $subscription['status'] == 'cancel') && time() <= strtotime($subscription['expiration_date'])) {
				$member_subscriptions[] = $subscription['subscription_plan_id'];
			}
		}
	}
 
    if (!empty($member_subscriptions))
		return true;
	else
		return false;
}
 
add_action( 'woocommerce_product_query', 'pmsc_exclude_products_created_by_expired_members' );
function pmsc_exclude_products_created_by_expired_members( $query ) {
	//if you add $query->is_tax() to the if, it will affect only the category pages; else it affects all queries including the shop page
	if( !is_admin() && function_exists('pms_is_post_restricted') && function_exists('pmsc_check_subscription') ) {
		$args = $query->query_vars;
		$args['suppress_filters'] = true;
		$args['posts_per_page'] = get_option( 'posts_per_page' );
 
		$products = wc_get_products($args);
 
		$product_ids = array();
		$restricted_ids = array();
 
		foreach ($products as $product) {
			$author = get_post_field( 'post_author', $product->get_id() );
 
			if ( !pmsc_check_subscription( $author ) )
				$restricted_ids[] = $product->get_id();
		}
 
		$query->set( 'post__not_in', $restricted_ids );
	}
}

If you don’t know how to use these code snippets, please read the instructions found at the top of this page.

The Ultimate Membership Bundle

Combine the power of Profile Builder with Paid Member Subscriptions to set up user registration, memberships, and recurring revenue.

Get 25% off with the bundle

Help & Support

We’re here to help you every step of the way.

Open a Support Ticket