Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 ?

share|improve this question
2  
Are you already saving user logins? If so, how? –  s_ha_dum Dec 1 '13 at 19:19

1 Answer 1

up vote 2 down vote accepted

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.

<?php
// 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(
                array(
                    'date_query' =>
                        array(
                            '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; ?>
<?php
// Restore original Post Data
wp_reset_postdata();
?>
share|improve this answer
    
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. –  Chittaranjan Dec 1 '13 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 ? –  Roee Yossef Dec 2 '13 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' ). –  Chittaranjan Dec 2 '13 at 12:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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