Highlighting The Comments Since Your Last Visit

WordPress comments have been the same for years, and it's time to upgrade them. This article covers a simple technique that uses a cookie to store the post ID and time since last visit. Based on that a class is added to the comment if it was made after the time stored in the cookie. Only one cookie is used and a JSON object is stored inside. We start by checking if the current page is singular and using json_decode and json_encode retrieve and store information from the cookie. Remember that the cookie function needs to be at the beginning of your theme's code.

<?php if( is_singular() ){

    // Get the current post/page ID and time
    $id = get_the_ID();
    $current_time = strtotime(current_time('mysql'));

    // If the cookie already exists make an array
    if (isset($_COOKIE['last_visit'])) {
        $latest_visit = json_decode(stripslashes($_COOKIE['last_visit']), true);

        // Don't let the cookie get too big, only keep the newest 50 posts
        if(count($latest_visit) >= 50){
            $latest_visit = array_diff($latest_visit, array(min($latest_visit)));

    // Save the new visit time for current ID in the array and set the cookie
    $latest_visit[$id] = $current_time;
    setcookie('last_visit', json_encode($latest_visit), time()+3600*2200);
} ?>

<!DOCTYPE html>

Now that the cookie is set let's edit the comments loop, usually it's placed in theme's comments.php or functions.php file. For example, in TwentyTwelve theme the line (283 / functions.php) looks like so:

comments.php or functions.php
<article id="comment-<?php comment_ID(); ?>" class="comment">

We're just gonna add an extra class "new-comment" if the comment time is greater than last visit time so replace the line above with this piece of code:

comments.php or functions.php
// Get the time for this single comment
$comment_time = strtotime(get_comment_date('Y-m-d G:i:s'));
$latest_visit = json_decode(stripslashes($_COOKIE['last_visit']), true);

// If the comment is posted after the user's last visit add a new class
if($comment_time > $latest_visit[get_the_ID()]){ ?>
    <article id="comment-<?php comment_ID(); ?>" class="comment new-comment">
<?php } else { ?>
    <article id="comment-<?php comment_ID(); ?>" class="comment">
<?php } ?>

With the code above, a new class called "new-comment" will be added to new comments and you can then use it to style them. For example, give it a fading green background:

    background-color: #E8FCE7;

Hopefully some of you will find this idea useful or maybe use the cookie-storing technique for something even more creative.