• Resolved farnely

    (@farnely)


    I’m developing a multi site installation. Some of my custom post types have a permanent status of “private”. I have used the template_redirect hook like this in code snippets on each site (and varying the function name in each case) to avoid a 404 if a logged out user requests a valid URL for a private custom post:-

    add_action( 'template_redirect', 'my_function_name' );
    function my_function_name() {
        if ( is_single( 'my-custom-post-type' ) && 'private' == get_post_status( get_the_id() ) && ! is_user_logged_in() ){
            $redirect = network_home_url( '/log-in/' );
            wp_safe_redirect( $redirect, 301 );
            exit;
        }
    }

    In tests, this works when the URL is for the main site. However, when the URL is for any other blog, a 404 is returned. Can anyone shed any light on this please?

    Many thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator threadi

    (@threadi)

    Are you using a multisite with paths or with subdomains?

    Check by debugging what is_user_logged_in() outputs where a 404 occurs. Also use a private browser where you are not logged into any of the sub-websites.

    Thread Starter farnely

    (@farnely)

    @threadi
    Thanks for your suggestions. Am using paths, private browser produced same result and is_user_logged_in() returns correct status on 404 page.

    Have been trying out a few more things and managed to solve it by updating my template_redirect hook to redirect if is_404(), user not logged in and the requested post exists. Narrowing it down any further (to specific custom post types, for example) returns the unwanted 404 again.

    This is as close as I can get to what I was trying to achieve so am closing thread.

    Moderator threadi

    (@threadi)

    You mean the check for is_single( ‘my-custom-post-type’ ) results in a false, although it shouldn’t? Then perhaps the custom post type is not yet registered when this position is called. Which hook do you use to register the custom post type?

    Thread Starter farnely

    (@farnely)

    I use a third party plugin for custom posts and fields so I don’t know what hook is used.

    I’m of the opinion, however, that the custom post type must be registered by the time the template_redirect hook runs because if I change the post status to publish, a 404 is not returned and the content template loads. I think that when the post status is private, the post is considered non-existent for a logged out user and logically you can’t fetch the post type for a non-existent post.

    Working with private posts in wordpress is cumbersome!

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Question about template_redirect hook’ is closed to new replies.