mww2

How to Display Last Visited Posts in WordPress (Beginner’s Guide)

Have you ever wanted to make it easy for visitors to return to posts they recently viewed on your website? Displaying recently visited posts on your WordPress site not only enhances usability but also helps keep returning users engaged. This guide will walk you through the steps to add this feature, whether you prefer using a plugin or custom code. Let’s dive in and enhance your visitors’ experience on your WordPress site!

Why Display Last Visited Posts?

Showing recently viewed posts is a simple yet effective way to improve user experience. Visitors often want to revisit material they found interesting without having to search again. This feature saves them time and effort, making your website feel more personal and welcoming. It invites users to stay longer on your site, significantly increasing page views and reducing bounce rates—a positive signal to search engines that can improve your site’s ranking.

Method 1: Use a Plugin to Show Last Visited Posts

Using a plugin is the easiest way to display the latest visited posts without coding. Here are popular plugins for this task:

WP Last Viewed Posts

This easy-to-use plugin tracks each user’s visited posts and displays them on your website. You can place them inside posts or in a widget.

How to use WP Last Viewed Posts:

  1. Go to your WordPress dashboard.
  2. Click Plugins > Add New.
  3. Search for WP Last Viewed Posts.
  4. Install and activate the plugin.
  5. Go to Appearance > Widgets.
  6. Add the Last Viewed Posts widget to your sidebar or footer.
  7. Customize the title and number of posts to show.
  8. Save your changes.

Now, visitors will see the posts they last visited in your chosen area.

Recently Viewed Products (For WooCommerce Sites)

If you run an online store, this plugin displays items a visitor has recently viewed, helping to boost sales by reminding guests of products they liked. Installation and widget configuration mirror the steps above.

Method 2: Use Custom Code to Show Last Visited Posts

For those who enjoy customizing, you can manually add this feature using code, which saves user data via cookies.

Step 1: Add Code to Track Visited Posts

Place this code in your theme’s functions.php file or a custom site plugin:

function track_visited_posts() {
  if (is_single()) {
    global $post;
    $visited = isset($_COOKIE['visited_posts']) ? explode(',', $_COOKIE['visited_posts']) : [];
    if (!in_array($post->ID, $visited)) {
      $visited[] = $post->ID;
    }
    if (count($visited) > 5) {
      array_shift($visited); // Keep only last 5 posts
    }
    setcookie('visited_posts', implode(',', $visited), time() + (30 * DAY_IN_SECONDS), COOKIEPATH, COOKIE_DOMAIN);
  }
}
add_action('template_redirect', 'track_visited_posts');

This code tracks the last five posts a visitor viewed using a cookie stored in their browser.

Step 2: Display the Last Visited Posts

Add this code where you want to show the list (e.g., in a sidebar widget):

function display_last_visited_posts() {
  if (isset($_COOKIE['visited_posts'])) {
    $visited = array_reverse(explode(',', $_COOKIE['visited_posts']));
    echo '<ul>';
    foreach ($visited as $post_id) {
      $post = get_post($post_id);
      if ($post) {
        $title = get_the_title($post);
        $link = get_permalink($post);
        echo "<li><a href='$link'>$title</a></li>";
      }
    }
    echo '</ul>';
  } else {
    echo 'No recently visited posts.';
  }
}

You can use this function directly in your theme template or insert it via a shortcode.

Step 3: Add Shortcode for Easier Use

To simplify usage, add this code:

add_shortcode('last_visited_posts', 'display_last_visited_posts');

Now, you can add [last_visited_posts] to any post or page to show the list.

Method 3: Use Browser Storage (Advanced)

While cookies work well, they have limits. An alternative is using localStorage in the browser, which stores data longer and doesn’t send information with every request.

Step 1: Add JavaScript to Track Posts

Insert this script in your theme footer or via a plugin:

<script>
document.addEventListener('DOMContentLoaded', function() {
  let visited = JSON.parse(localStorage.getItem('visitedPosts') || '[]');
  let postId = '<?php echo get_the_ID(); ?>';
  if (!visited.includes(postId)) {
    visited.push(postId);
    if (visited.length > 5) {
      visited.shift();
    }
    localStorage.setItem('visitedPosts', JSON.stringify(visited));
  }
});
</script>

Step 2: Show Visited Posts with JavaScript

Add this script where you want the list to appear:

<div id="visited-posts"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
  let visited = JSON.parse(localStorage.getItem('visitedPosts') || '[]').reverse();
  let container = document.getElementById('visited-posts');
  if (visited.length === 0) {
    container.innerHTML = 'No recently visited posts.';
    return;
  }
  let html = '<ul>';
  visited.forEach(function(postId) {
    fetch('/?p=' + postId + '&_embed').then(response => response.json()).then(data => {
      let title = data.title.rendered;
      let link = data.link;
      html += `<li><a href="${link}">${title}</a></li>`;
      container.innerHTML = html + '</ul>';
    }).catch(() => {
      container.innerHTML = 'Error loading posts.';
    });
  });
});
</script>

This advanced method requires your site to support REST API calls.

Conclusion

Displaying the latest visited posts on your WordPress site is an excellent way to enhance user experience. It keeps guests engaged longer and provides quick access to previously viewed content. Whether you choose plugins, custom code, or browser storage, each method offers unique advantages. Plugins are user-friendly for beginners, while code offers more control. Though more advanced, browser storage is a powerful option. Implementing this feature will elevate the professionalism and usability of your website. Try one of these techniques to help your visitors explore more of your content and enhance their journey.