Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ipokkel/b9879bdf767a170331a659fc4bb98136 to your computer and use it in GitHub Desktop.
Save ipokkel/b9879bdf767a170331a659fc4bb98136 to your computer and use it in GitHub Desktop.
On WordPress login, redirect to the last post you were viewing or custom page if no last page available
<?php
/**
* On login, redirect to the last post viewed or custom page if no last page available.
* Add this code into a custom plugin.
* Note that many themes and plugins hook into login_redirect.
* Whichever hook has the highest priority will be the last call
* on where to redirect. The priority below is set to 20.
* Note also that some URLs/pages may note be "posts"
* and may not have an ID we can track.
* Note also that some pages are excluded. You may want to exclude other pages.
* Note also that this may override any specific redirect_to passed in
* by URL parameter.
*/
/**
* Remember last post ID
*/
function my_remember_last_post_id() {
global $pmpro_pages;
$queried_object = get_queried_object();
// don't need to track if already logged in
if ( is_user_logged_in() ) {
return;
}
// no post?
if ( empty( $queried_object ) || empty( $queried_object->ID ) ) {
return;
}
// don't track the login page
if ( function_exists( 'pmpro_is_login_page' ) && pmpro_is_login_page() ) {
return;
}
// don't track pmpro pages
if ( is_array( $pmpro_pages ) && in_array( $queried_object->ID, $pmpro_pages ) ) {
return;
}
// Okay set it
setcookie( 'last_post_viewed', $queried_object->ID, null, '/' );
}
add_action( 'wp', 'my_remember_last_post_id' );
/**
* On login, redirect to the last post viewed.
*/
function my_redirect_to_last_post_id( $redirect_to, $request, $user ) {
// If no redirect already, use the last page viewed
if ( ! empty( $_COOKIE['last_post_viewed'] ) ) {
$redirect_to = get_permalink( intval( $_COOKIE['last_post_viewed'] ) );
} else {
$redirect_to = home_url( 'community' );
}
return $redirect_to;
}
add_filter( 'login_redirect', 'my_redirect_to_last_post_id', 20, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment