Skip to content

Instantly share code, notes, and snippets.

@andrewlimaza
Last active February 21, 2023 11:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewlimaza/d03ecc4441385fa40debdc73ceb2d569 to your computer and use it in GitHub Desktop.
Save andrewlimaza/d03ecc4441385fa40debdc73ceb2d569 to your computer and use it in GitHub Desktop.
Filter your WooCommerce store according to membership level for Paid Memberships Pro.
<?php
/**
* This code recipe will allow you to hide products on the shop page by their category according to user's membership levels.
* This example uses category-1, category-2 and category-3 as category examples.
* This code will also stop users from purchasing products if they manage to find these products directly.
* Add this code (from line 2) to your PMPro Customizations Plugin - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
/**
* This function simply removes products from shop based on membership level.
*/
function pmpro_remove_product_from_shop( $q ) {
//Ignore if user is admin.
if( current_user_can( 'manage_options' ) ){
return $q;
}
if ( pmpro_hasMembershipLevel( 1 ) ) {
$hide_these_categories = array( 'category-1', 'category-3' );
}
if ( pmpro_hasMembershipLevel( 2 ) ) {
$hide_these_categories = array( 'category-2' );
}
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $hide_these_categories,
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'pmpro_remove_product_from_shop' );
/**
* This function stops user's from purchasing the product, this will help if the user's navigate directly to the product.
*/
function pmpro_stop_product_purchase( $is_purchasable, $product ) {
// Check if the user has an active membership level.
if( current_user_can( 'manage_options' ) ) {
return $is_purchasable;
}
if ( pmpro_hasMembershipLevel( 1 ) ) {
// Adjust the restricted categories that require membership level to purchase. Use category-slug.
$restricted_category_slugs = array(
'category-1',
'category-3'
);
}
if ( pmpro_hasMembershipLevel( 2 ) ) {
$restricted_category_slugs = array(
'category-2'
);
}
if( if( has_term( $restricted_category_slugs, 'product_cat', $product->get_id()) ) ) {
$is_purchasable = false;
}
return $is_purchasable;
}
add_filter( 'woocommerce_is_purchasable', 'pmpro_stop_product_purchase', 10, 2 );
@fabianski7
Copy link

for me works only after i edit

if( has_term( $restricted_category_slugs, 'product_cat') )

to

if( has_term( $restricted_category_slugs, 'product_cat', $product->get_id()) )

@andrewlimaza
Copy link
Author

Thanks this has been updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment