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
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)));
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With