Created
July 1, 2020 22:39
-
-
Save ideadude/91ea968f0be625cb1c8fdf07d2377edf to your computer and use it in GitHub Desktop.
Change the default PMPro WooCommerce bahavior and make membership products not purchasable if a user already has any other membership level.
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 | |
/** | |
* Change the default PMPro WooCommerce bahavior | |
* and make membership products not purchasable | |
* if a user already has any other membership level. | |
*/ | |
// First disable the core PMPro WC callaback and set up our own. | |
function my_pmprowoo_init() { | |
remove_filter( 'woocommerce_is_purchasable', 'pmprowoo_is_purchasable', 10, 2 ); | |
add_filter( 'woocommerce_is_purchasable', 'my_pmprowoo_is_purchasable', 5, 2 ); | |
} | |
add_action( 'init', 'my_pmprowoo_init' ); | |
// Our new callback. | |
function my_pmprowoo_is_purchasable( $is_purchasable, $product ) { | |
global $pmprowoo_product_levels; | |
// Bail if PMPro or PMPro WC is not active. | |
if ( ! function_exists( 'pmpro_hasMembershipLevel' ) || ! function_exists( 'pmprowoo_cart_has_membership' ) ) { | |
return $is_purchasable; | |
} | |
// Not purchasable for some other reason. | |
if( ! $is_purchasable ) { | |
return $is_purchasable; | |
} | |
// This is the main line that was changed from default PMPro WC | |
$has_membership = pmprowoo_cart_has_membership() || pmpro_hasMembershipLevel(); | |
$product_id = $product->get_id(); | |
$is_purchasable = ( in_array( $product_id, array_keys( $pmprowoo_product_levels ) ) && true === $has_membership ? false : $is_purchasable ); | |
// Add the warning message for the single product summary page(s) | |
if ( false === $is_purchasable ) { | |
if ( pmpro_hasMembershipLevel() ) { | |
add_action( 'woocommerce_single_product_summary', 'my_pmprowoo_purchase_disabled' ); | |
} else { | |
add_action( 'woocommerce_single_product_summary', 'pmprowoo_purchase_disabled' ); | |
} | |
} | |
return $is_purchasable; | |
} | |
// Show already have membership version of the disabled message. | |
function my_pmprowoo_purchase_disabled() { | |
?> | |
<div class="woocommerce"> | |
<div class="woocommerce-info wc-nonpurchasable-message"> | |
<?php _e( "You already have a membership level.", 'pmpro-woocommerce' ); ?> | |
</div> | |
</div> | |
<?php | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment