Site logo

Archived topic

Redirect logged out users from a custom post archive

3 replies · Started by Rekindle on October 18, 2021

Viewing posts 1–4 of 4

Hi,

I have used the GP Content block to style the archive page for one of my custom post types. I'd like to restrict that page to logged-in users only. But I can't edit it like a regular page, so I can't use the standard plugin I use to restrict specific pages to logged-in users.

Is there a nifty GP way to do this? If not, I've written this code snippet:

add_action( 'template_redirect', 'pa_redirect_from_selfjournal', 10, 0 );

function pa_redirect_from_selfjournal() {
	$pl = get_permalink();
	error_log( 'Permalink: ' . $pl );
	if ( ! basename( get_permalink() === 'selfjournal' ) ) :
		return;
	endif;
	if ( is_user_logged_in() ) :
		return;
	endif;
	wp_safe_redirect( home_url() );
	exit;
}

The issue is that the get_permalink() function returns the permalink of the first custom post within this archive (so something like /selfjournal/1 instead of /selfjournal/). How do I fix this?

Thanks!

Hi there,

I believe the condition to check for the specific post type archive and if user is not logged in would be this:

if( is_post_type_archive( 'your-cpt-slug' ) && !is_user_logged_in() )

So for example, if I'd like to redirect user to the home page if they try to access CPT with slug 'movies' when they aren't logged in, here's something that could work.

add_action( 'template_redirect', 'redirect_to_home', 10 );

function redirect_to_home() {
	if( is_post_type_archive( 'movies' ) && !is_user_logged_in() ){
        wp_safe_redirect( home_url() );
	}
}

That fixed it, Elvin. Thanks!

No problem. glad to be of any help. :D

This archived topic is closed to new replies.