Forked from travislima/exclude-discount-woocommerce-categories.php
Last active
July 3, 2025 14:16
-
-
Save kimwhite/83a4ae6d00b434240507973f66c60310 to your computer and use it in GitHub Desktop.
Apply membership discount for products by a specific category (all other categories excluded)
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 // do not copy this line. | |
/** | |
* Apply membership discount ONLY to Woo products in specific allowed categories. | |
* All other categories will use the original (non-discounted) price. | |
* | |
* You can add this recipe to your site by creating a custom plugin | |
* or using the Code Snippets plugin available for free in the WordPress repository. | |
* Read this companion article for step-by-step directions on either method. | |
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
*/ | |
function my_pmpro_only_discount_selected_categories( $price, $level_id, $original_price, $product ) { | |
// Array of allowed category slugs. | |
$allowed_categories = array( 'india' ); // Add more slugs as needed, e.g., 'india', 'nepal' | |
// Get the product ID (parent if variation). | |
$product_id = ( $product->get_type() === 'variation' ) ? $product->get_parent_id() : $product->get_id(); | |
// Get category terms for the product. | |
$category_data = wp_get_post_terms( $product_id, 'product_cat' ); | |
$has_allowed_category = false; | |
foreach ( $category_data as $term ) { | |
if ( in_array( $term->slug, $allowed_categories, true ) ) { | |
$has_allowed_category = true; | |
break; | |
} | |
} | |
// If product is not in any allowed category, revert to original price. | |
if ( ! $has_allowed_category ) { | |
$price = $original_price; | |
} | |
return $price; | |
} | |
add_filter( 'pmprowoo_get_membership_price', 'my_pmpro_only_discount_selected_categories', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment