To hide specific pages from non-logged-in users in WordPress, you can use the template_redirect
action hook to redirect them to another page or display a custom message. Here’s an example of how you can achieve this:
function wpsnippets_hide_pages_from_non_logged_in_users() {
// Define the ID's of the pages to hide
$pages_to_hide = array( 35, 57, 328 );
// Check if the user is not logged in, and if the current page should be hidden
if ( ! is_user_logged_in() && is_page( $pages_to_hide ) ) {
// Redirect to the home page
wp_safe_redirect( home_url() );
exit;
}
}
add_action( 'template_redirect', 'wpsnippets_hide_pages_from_non_logged_in_users' );
In this example, we define the pages with the IDs 35
, 57
, and 328
as those you want to hide from non-logged-in users. Replace them with the slugs or IDs of the pages you want to exclude.
Inside the wpsnippets_hide_pages_from_non_logged_in_users()
function, the is_user_logged_in()
function is used to check if the user is not logged in. Then, the is_page()
function is used to check if the current page matches the specified slugs or IDs. If both conditions are met, the user is redirected to the home page using wp_redirect()
, and exit()
is called to terminate further execution.
By adding this code snippet to your WordPress site, you can hide the specified pages unless the user is logged in. When non-logged-in users try to access those pages, they will be redirected to the home page or any other URL you specify in wp_safe_redirect()
.