Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect private page to login first then display page in Wordpress

I have several Private pages that linked from my public pages. By default when a non-logged in user clicks on one of these links they get a a 404 page. I'd like for them to get a login page and then continue on to the page they requested.

Pete's Redirect plugin is great but it wants to go to specifically designated pages per user/role after login. I'd like to just continue on to the page they requested.

Any suggestions? thanks, rich

like image 907
user2887097 Avatar asked Dec 26 '22 17:12

user2887097


2 Answers

This is the right way to do

add_action('wp', 'redirect_private_page_to_login');

function redirect_private_page_to_login(){

    global $wp_query;

    $queried_object = get_queried_object();

    if ($queried_object->post_status == "private" && !is_user_logged_in()) {

        wp_redirect(home_url('/login?redirect='.get_permalink($queried_object->ID)));

    } 
}
like image 186
Tu Bui Avatar answered Jan 14 '23 04:01

Tu Bui


I had a few problems with Tu Bui's answer. Here is an improved version.

add_action( 'wp', 'redirect_private_page_to_login' );
function redirect_private_page_to_login(){
    $queried_object = get_queried_object();
    if (
        isset( $queried_object->post_status ) &&
        'private' === $queried_object->post_status &&
        ! is_user_logged_in()
    ) {
        wp_safe_redirect( wp_login_url( get_permalink( $queried_object->ID ) ) );
        exit;
    }
}

Here is the same code in a small plugin: https://github.com/wearerequired/private-page-login

like image 21
grappler Avatar answered Jan 14 '23 03:01

grappler