Forked from andrewlimaza/pmpro_redirect_away_from_product_non_members.php
Last active
April 7, 2025 12:02
-
-
Save davidmutero/668c5cf2fd66050599f7b18a97398837 to your computer and use it in GitHub Desktop.
Restrict Direct Access to WooCommerce Products by Category and Membership Level with Paid Memberships Pro
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 | |
/** | |
* This stops users from accessing restricted products directly with Paid Memberships Pro. | |
* Tested on WooCommerce 3.4 and up. | |
* You may be interested with the following gist for removing products from WooCommerce shop page - https://gist.github.com/andrewlimaza/6ee480694d38a99695503febe3cdabf1 | |
* Add the following function to your PMPro Customizations plugin - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
* Visit https://www.paidmembershipspro.com for any questions or assistance. | |
*/ | |
function pmpro_redirect_away_from_restricted_product() { | |
if ( ! is_product() || is_admin() ) { | |
return; | |
} | |
global $post; | |
// Define restricted product categories. | |
$restricted_cats = array( 'category-one', 'category-two' ); // Update slugs as needed. | |
// Define allowed PMPro membership levels. | |
$allowed_levels = array( 2, 3 ); // Update to match your level IDs. | |
// If the user does not have an allowed level and the product is in a restricted category, redirect them. | |
if ( ! pmpro_hasMembershipLevel( $allowed_levels ) && has_term( $restricted_cats, 'product_cat', $post->ID ) ) { | |
wp_redirect( home_url( '/membership-levels/' ) ); | |
exit; | |
} | |
} | |
add_action( 'template_redirect', 'pmpro_redirect_away_from_restricted_product' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment