Created
February 26, 2026 12:37
-
-
Save JarrydLong/3c82a9d386b51c1527542c0c2cffb17d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 //do not copy | |
| /* This recipe hide any products from the Woo store if the current member | |
| * does not have access to the product with a level restriction | |
| * | |
| * You can add this recipe to your site by creating a custom plugin | |
| * or using the Code Snippets plugin available for free in the WordPress repository. | |
| * Read this companion article for step-by-step directions on either method. | |
| * https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
| */ | |
| function my_pmpro_hide_woo_restricted_products( $q ) { | |
| if ( is_admin() ) { | |
| return; | |
| } | |
| if ( ! function_exists( 'pmpro_getMembershipLevelsForUser' ) ) { | |
| return; | |
| } | |
| global $wpdb; | |
| // Get current user levels | |
| $user_levels = pmpro_getMembershipLevelsForUser(); | |
| $user_level_ids = []; | |
| if ( ! empty( $user_levels ) ) { | |
| foreach ( $user_levels as $level ) { | |
| $user_level_ids[] = (int) $level->ID; | |
| } | |
| } | |
| // Get all restricted product IDs | |
| $restricted_products = $wpdb->get_col(" | |
| SELECT page_id | |
| FROM {$wpdb->pmpro_memberships_pages} | |
| "); | |
| if ( empty( $restricted_products ) ) { | |
| return; | |
| } | |
| // If user has NO membership | |
| if ( empty( $user_level_ids ) ) { | |
| $q->set( 'post__not_in', $restricted_products ); | |
| return; | |
| } | |
| // Get products user IS allowed to see | |
| $allowed_products = $wpdb->get_col( $wpdb->prepare(" | |
| SELECT page_id | |
| FROM {$wpdb->pmpro_memberships_pages} | |
| WHERE membership_id IN (" . implode(',', array_fill(0, count($user_level_ids), '%d')) . ") | |
| ", $user_level_ids ) ); | |
| // Products restricted but not allowed | |
| $disallowed_products = array_diff( $restricted_products, $allowed_products ); | |
| if ( ! empty( $disallowed_products ) ) { | |
| $q->set( 'post__not_in', $disallowed_products ); | |
| } | |
| } | |
| add_action( 'woocommerce_product_query', 'my_pmpro_hide_woo_restricted_products' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment