1

I would like to redirect all non-logged in users to a specific page if they are directly trying to access:

  • Any category archive
  • Any tag archive
  • Any single post

I'm trying to use this code in child theme's functions.php, but it is not working.

add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
    if ( is_page_template( 'single-post' ) && ! is_user_logged_in() ) {
        wp_redirect( '/', 301 );
        exit;
    }
}
0

Here's an updated version of the code that successfully redirects users who are not logged in to a specific page when they try and view a tag or category archive or a singular post.

add_action( 'template_redirect', 'wpse_redirect_to_specific_page' );
function wpse_redirect_to_specific_page() {
    // Bail if the user is logged in.
    if ( is_user_logged_in() ) {
        return;
    }

    // Redirect to a special page if the user is trying to access
    // a category or tag archive or a single post.
    if ( is_category() || is_tag() || is_singular( 'post' ) ) {

        // Set the ID of the page to redirect to.
        // Change the ID to the desired page to redirect to.
        $redirect_to_page_id = 1086;

        wp_safe_redirect( get_permalink( $redirect_to_page_id ), 301 );
        exit;
    }
}

Handling custom taxonomies

If you'd like to redirect custom taxonomy archive pages, you could add is_tax() to the conditional statement that wraps the redirect code.

Handling custom post types

If you'd like to do the same for all post type singular pages, you could use is_singular() without passing the post parameter, or for specific post types, pass an array of post type names.

  • Worked perfectly! Thanx! But, as a relative newbie on this stuff, I am curious how I would go about defining specific cats and tags. I tried to add them in this way, but it didnt work. What am I doing wrong? if ( is_category('test','test-2') – Odell Jul 10 '17 at 13:44
  • Glad to hear! Your'e on the right track, but pass multiple category or tag slugs as an array, e.g. is_category( array( 'test', 'test-2' ) ). – Dave Romsey Jul 10 '17 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.