[Resolved] Redirect logged out users from a custom post archive

Home Forums Support [Resolved] Redirect logged out users from a custom post archive

Home Forums Support Redirect logged out users from a custom post archive

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #1967926
    Rekindle

    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!

    #1967931
    Elvin
    Staff
    Customer Support

    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() );
    	}
    }
    #1967941
    Rekindle

    That fixed it, Elvin. Thanks!

    #1967943
    Elvin
    Staff
    Customer Support

    No problem. glad to be of any help. 😀

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.