Created
November 20, 2020 14:49
-
-
Save ronalfy/a4bcaef67dd3fbd3d7237b9bd0d0a1b2 to your computer and use it in GitHub Desktop.
PMPro - Restrict Categories on Sub-site in a Multisite Network
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 | |
/** | |
* Restrict categories on the sub-site of a MS network. | |
* Install as an mu-plugin (advanced users only) | |
*/ | |
function my_pmpro_member_pmpro_has_membership_access_filter( $access, $post, $user, $levels ) { | |
// If main site, leave alone. | |
if ( is_main_site() || is_admin() ) { | |
return $access; | |
} | |
// Get post object. | |
global $post; | |
if ( 'post' !== get_post_type() ) { | |
return $access; | |
} | |
// Levels and categories to restrict. | |
$categories_to_restrict = array( | |
1 => array( // level ID. | |
'general', // category slug. | |
'uncategorized', | |
), | |
2 => array( | |
'general', | |
'restricted', | |
), | |
); | |
$maybe_has_term = false; | |
foreach ( $categories_to_restrict as $level_id => $categories ) { | |
foreach ( $categories as $cat ) { | |
if ( has_term( $cat, 'category', $post ) ) { | |
$maybe_has_term = true; | |
} | |
} | |
} | |
if ( ! is_user_logged_in() && $maybe_has_term ) { | |
return false; | |
} | |
// Get current level. | |
global $current_user; | |
$level = pmpro_getMembershipLevelForUser( $current_user->ID ); | |
// Return false on failure (no level). | |
if ( ! $level ) { | |
return false; | |
} | |
// If cat is set, see if in the restriction array. | |
if ( $maybe_has_term && ! isset( $categories_to_restrict[ $level->id ] ) ) { | |
return false; | |
} | |
// Nothing found, return as normal. | |
return $access; | |
} | |
add_filter( 'pmpro_has_membership_access_filter', 'my_pmpro_member_pmpro_has_membership_access_filter', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment