Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ideadude/31b3a8f763684790541f2ce6b7d230e8 to your computer and use it in GitHub Desktop.
Save ideadude/31b3a8f763684790541f2ce6b7d230e8 to your computer and use it in GitHub Desktop.
Prevent non-members from adding member products to their cart with WooCommerce and PMPro.
<?php
/**
* Prevent non-members from adding member products to their cart.
* This requires the PMPro CPT Add On be installed and
* each product should be checked for which levels are required.
*/
function my_keep_members_only_products_out_of_carts( $is_purchasable, $product ) {
// Not purchasable for some other reason.
if( ! $is_purchasable ) {
return $is_purchasable;
}
// Make sure PMPro is active.
if ( ! function_exists( 'pmpro_has_membership_access' ) ) {
return $is_purchasable;
}
$product_id = $product->get_id();
$has_access = pmpro_has_membership_access( $product_id );
$is_purchasable = $has_access;
if ( false === $has_access ) {
// Add the warning message for the single product summary page(s)
add_action( 'woocommerce_single_product_summary', 'my_pmprowoo_purchase_disabled' );
}
return $is_purchasable;
}
add_filter( 'woocommerce_is_purchasable', 'my_keep_members_only_products_out_of_carts', 10, 2 );
/**
* Info message when attempting to add non-member product to your cart.
*/
function my_pmprowoo_purchase_disabled() {
?>
<div class="woocommerce">
<div class="woocommerce-info wc-nonpurchasable-message">
This product is for members only.
</div>
</div>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment