I'm looking for a solution to create a custom loop which will only display the last added/ modified posts since the last user login to the site.

It shouldn't be that complicated doesnt it ?

  • 2
    Are you already saving user logins? If so, how?
    – s_ha_dum
    Commented Dec 1, 2013 at 19:19

1 Answer 1


Getting the posts after a specific time will be done in 2 steps.

  1. You need to store the last login time of the user.
  2. Changing the query to pull the posts which are modified after the above login time.

The below function will store the last login time of the user.

// Associating a function to login hook
add_action ( 'wp_login', 'set_last_login' );

function set_last_login ( $login ) {
    $user = get_userdatabylogin ( $login );

    // Setting the last login of the user
    update_usermeta ( $user->ID, 'last_login', date ( 'Y-m-d H:i:s' ) );

Then you need to collect the last login time of the logged in user and modify the query as below.

// Get current user object
$current_user = wp_get_current_user();

// Get the last login time of the user
$last_login_time = get_user_meta ( $current_user->ID, 'last_login', true );

// WP_Query with post modified time
$the_query = new WP_Query(
                    'date_query' =>
                            'column' => 'post_modified',
                            'after' => $last_login_time,
<?php if ( $the_query->have_posts() ) : ?>

    <?php // Start the Loop ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <?php // Show the output ?>
    <?php endwhile; ?>

<?php endif; ?>
// Restore original Post Data
  • The above code will also work for newly added posts since on adding a new post the post_modified time is set same as post_date time. Commented Dec 1, 2013 at 21:16
  • This is working great, Thank you ! i'm on GMT+2 can you tell me how can i modified the last login time to use it ? Commented Dec 2, 2013 at 11:51
  • Can you check by using current_time ( 'mysql' ) instead of date ( 'Y-m-d H:i:s' ) in the set_last_login function? If that does not work, you can check with current_time ( 'timestamp' ). Commented Dec 2, 2013 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.