Last active
January 30, 2020 11:09
-
-
Save ideadude/d574e1f75deb589c1161217b0111efb9 to your computer and use it in GitHub Desktop.
On WordPress login, redirect to the last post you were viewing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* On login, redirect to the last post viewed. | |
* 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'] ) ); | |
} | |
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