Forked from andrewlimaza/restrict-all-pages-non-members.php
Last active
October 3, 2023 15:31
-
-
Save ipokkel/d53b6ce05ec4ead241dd74f0caed4cf2 to your computer and use it in GitHub Desktop.
Restrict all pages except home, Paid Memberships Pro pages, and specific pages for non-members.
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 | |
/** | |
* This recipe will restrict all pages except Paid Memberships Pro pages, | |
* or the home page of your website, the search results page, the 404 page, or defined post/pages to non-members, | |
* non-approved members, or logged-out users. | |
* | |
* This won't affect administrators. | |
* | |
* 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_redirect_non_members() { | |
$allowed_post_ids = array( 2, 35, 27, 55 ); // set the Post ID of your allowed pages, e.g. Contact Us, here. | |
global $pmpro_pages; | |
if ( is_search() || is_404() || in_array( get_the_ID(), $allowed_post_ids ) || is_page( $pmpro_pages ) || is_home() || current_user_can( 'manage_options' ) ) { | |
return; | |
} | |
$access = false; | |
global $current_user, $pmpro_pages; | |
$user_id = $current_user->ID; | |
if ( ! empty( $user_id ) ) { | |
// Get approval status | |
if ( class_exists( 'PMPro_Approvals' ) ) { | |
$approval = PMPro_Approvals::getUserApproval( $user_id ); | |
// User currently does not need approval. | |
if ( empty( $approval ) ) { | |
return; | |
} | |
$approval_status = $approval['status']; | |
if ( ! empty( $approval_status ) && $approval_status != 'approved' ) { | |
$access = false; | |
} else { | |
$access = true; | |
} | |
} | |
// Make sure logged-in non-members don't have access. | |
if ( ! pmpro_hasMembershipLevel() ) { | |
$access = false; | |
} | |
} | |
// if the user is not approved, redirect to BuddyPress restricted page or home page if add on not enabled. | |
if ( ! $access ) { | |
wp_redirect( home_url() ); | |
exit; | |
} | |
} | |
add_action( 'template_redirect', 'my_pmpro_redirect_non_members', 45 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment