yan-k
1/19/2017 - 10:29 PM

WooCommerce Memberships filter to check if a products should be displayed to a user. Only display the product to active members of the plan

WooCommerce Memberships filter to check if a products should be displayed to a user.

Only display the product to active members of the plan.

<?php

add_filter( 'woocommerce_product_is_visible', 'yanco_check_membership_product_visibility', 10, 2 );
function yanco_check_membership_product_visibility( $visible, $product_id ) {
	if( function_exists('wc_memberships') ) {
		$user = wp_get_current_user();

		if ( in_array( 'shop_manager', (array) $user->roles ) ) {
			return $visible;
		}

		if ( in_array( 'administrator', (array) $user->roles ) ) {
			return $visible;
		}

		if ( wc_memberships_is_product_viewing_restricted( $product->ID ) ) {
			$user_plans = ( function_exists( 'wc_memberships_get_user_active_memberships' ) ) ? wc_memberships_get_user_active_memberships( $user->ID ) : 0;

			if ( ! empty( $user_plans ) && is_array( $user_plans ) && class_exists( 'WC_Memberships_Membership_Plan' ) ) {

				foreach( $user_plans as $user_plan ) {
					$plan = new WC_Memberships_Membership_Plan( intval( $user_plan->plan_id ) );
					$restricted_products = $plan->get_restricted_products();

					foreach( $restricted_products->posts as $restricted_product ) {

						if ( $restricted_product->ID == $product->ID ) {
							return false;
						} else {
							return $visible;
						}

					}
				}
			} else {
				return false;
			}
		}
	}
	return $visible;
}