Last active
July 2, 2019 22:32
-
-
Save andrewlimaza/809ff896e7b397d28738594e69795f99 to your computer and use it in GitHub Desktop.
Restrict particular product for WooCommerce and Paid Memberships Pro
This file contains 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 function allows you to restrict a single WooCommerce product to non-members (disables add to cart button) | |
* Price will still be displayed. | |
* Add the following code to your PMPro Customizations Plugin - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
*/ | |
function hide_add_to_cart_for_non_members( ){ | |
//try to get current product | |
$product = get_product(); | |
//ignore if product is empty or if user is administrator | |
if( empty( $product ) || current_user_can( 'manage_options' ) ) { | |
return; | |
} | |
//change your product ID you would like to restrict for members. | |
if( 31 === $product->id ) { | |
if( !pmpro_hasMembershipLevel() ) { | |
//remove the add to cart button | |
remove_action( 'woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30 ); | |
} | |
} | |
} | |
add_action( 'wp', 'hide_add_to_cart_for_non_members' ); | |
function remove_product_from_shop( $q ) { | |
//if user has a membership or is admin, leave the query alone. | |
if( pmpro_hasMembershipLevel() || current_user_can( 'manage_options' ) ){ | |
return $q; | |
} | |
$tax_query = (array) $q->get( 'tax_query' ); | |
$tax_query[] = array( | |
'taxonomy' => 'product_cat', | |
'field' => 'slug', | |
'terms' => array( 'change-this' ), //change this to category you would like to hide from shop page. | |
'operator' => 'NOT IN' | |
); | |
$q->set( 'tax_query', $tax_query ); | |
} | |
add_action( 'woocommerce_product_query', 'remove_product_from_shop' ); |
Hey @Jamesrobert27
I think the best way is to check if the product belongs to a specific category.
Have a look at this gist -> https://gist.github.com/andrewlimaza/d03ecc4441385fa40debdc73ceb2d569
Sorry I don't get notified on my gists :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! What if I want to restrict more than one product. How do i go about it?. Thanks!