0

When non-logged-in users attempt to go to a forum topic that requires a login, I'm trying to redirect them to that topic after they've logged in. But I can't seem to get the anchor/hashtag to remain in the URL so that the user goes right to the most recent comment.

Despite what I've tried below, the hashtag in the WordPress "redirect_to" parameter remains an actual hashtag instead of "%23". If I type "%23" into the "redirect_to" parameter in the browser, then the user goes right to the applicable anchor.

add_action( 'template_redirect', 'redirect_to_topic_after_login');
function redirect_to_topic_after_login() {

$destination_url = "https://www.domain.com/wp-login.php?redirect_to=" . $_SERVER['REQUEST_URI']; 

$destination_url = str_replace('%23', "#", $destination_url); //DIDN'T WORK
$destination_url = urlencode($destination_url); //DIDN'T WORK

if ( is_404() ) {wp_safe_redirect( $destination_url ); exit;}
}

In other words, I end up with https://www.domain.com/permalink/#abc instead of this https://www.domain.com%2Fpermalink%2F%23abc

0
function after_login_redirect_to_destination(){
    if (!is_user_logged_in() && !is_home()){
        $redirect = home_url() . '/wp-login.php?redirect_to=' . urlencode( $_SERVER['REQUEST_URI'] );
        wp_redirect( $redirect );
        exit;
    }
}
add_action( 'wp', 'after_login_redirect_to_destination', 3 );

the above sample code works and redirect to the login page and after successfull login it will redirect to home page. Whenever a non-logged in user try to access the home page, it will redirect to the login page and after successfull login then it will redirect back to destination page. Here the destination page(home page in this case) . You can modify the code above to your redirect to your custom login page and after success it will then redirect to the current page you were

Hope that helps!

  • The issue is that the hashtag doesn't remain in the redirect after login, even when I've used urlencode. – Sinclair Jun 7 '17 at 11:48

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.