• Resolved najfeez

    (@najfeez)


    Hi all,

    I’m trying to display a post count of new posts to logged in users, but I don’t want to display the total number of posts. Just the ones that are new since the last time the user logged out. Is this possible to do, and how to do it?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Getting the posts after a specific time can be achieved with 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. Currently it shows a list of posts but you should easily be able to modify this to output a number by counting the number of times it goes through the loop.

    <?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();
    ?>
    Thread Starter najfeez

    (@najfeez)

    This is awesome! thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Showing new posts count since last login’ is closed to new replies.