Skip to content

Instantly share code, notes, and snippets.

@andrewlimaza
Last active September 12, 2023 12:43
Show Gist options
  • Save andrewlimaza/6d8d9edd2ca31c258f00e8bc6292f797 to your computer and use it in GitHub Desktop.
Save andrewlimaza/6d8d9edd2ca31c258f00e8bc6292f797 to your computer and use it in GitHub Desktop.
Hide posts with certain category from members.
<?php
/**
* This code allows you to filter the default blog (archive) page to hide posts with certain category ID's from members.
* This is useful if you want to hide free content from paying members.
* Adjust line 16 & 21 to your needs. If the user does not have a membership level, the posts page won't be filtered/changed.
*
* Add the code below to your PMPro Customizations Plugin - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
* Reference: https://developer.wordpress.org/reference/hooks/pre_get_posts/
* www.paidmembershipspro.com
*/
function pmpro_exclude_categories_for_members( $query ) {
if ( function_exists( 'pmpro_hasMembershipLevel' ) ) {
if ( ! pmpro_hasMembershipLevel() ) {
return $query; // You may also adjust the $query for your needs for non-members/non-access users.
}
}
if ( ( $query->is_home() && $query->is_main_query() ) || ( is_search() && '' != $query->query_vars['s'] ) ) {
$query->set( 'cat', '-2,-3,-4' ); // Category ID's to exclude for members.
}
}
add_action( 'pre_get_posts', 'pmpro_exclude_categories_for_members' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment