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 ?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Getting the posts after a specific time will be done in 2 steps.
- You need to store the last login time of the user.
- 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();
?>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0