How to 301 private posts rather than 404?

How do I 301 redirect private pages, rather than 404 them? If a post is private, WordPress filters it out in the SQL query, so there are no $post variables to work with.

I’d like for this code to work, but doesn’t:

add_action('wp','redirect_stuffs', 0);
function redirect_stuffs(){
global $post;
    if ( $post->post_status == "private" && !is_admin() ):
        wp_redirect("http://dangayle.com/",301);
        exit();
    endif;
}

I don’t know where that is set earlier than wp, other than the fact that I know it’s a user role issue. If I could set a non-logged in user to have that capability, it would probably fix the issue:

$publicReader -> add_cap('read_private_posts');

The problem with add_cap is that only logged-in users have capabilities.

3 s
3

Sorry guys, I found my answer:

add_action('wp','redirect_stuffs', 0);
function redirect_stuffs(){
global $wpdb; 
    if ($wpdb->last_result[0]->post_status == "private" && !is_admin() ):
        wp_redirect( home_url(), 301 );
        exit();
    endif;
}

Posts/Pages are removed from the sitemaps, but the page still shows up on the site so that it can get 301’d.

Leave a Comment