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

How to Show Last Visited Posts in WordPress (Beginner’s Guide)
WordPress, the world’s leading content management system (CMS), offers incredible flexibility and customization options. One common request from website owners is to display recently viewed posts, allowing visitors to quickly revisit content they found interesting. This beginner’s guide will walk you through several methods to achieve this, catering to various skill levels, from plugin installation to basic coding.
Why Show Last Visited Posts?
Before diving into the how-to, let’s understand the “why.” Displaying recently viewed posts offers several benefits:
- Improved User Experience: Helps users easily find content they previously engaged with, reducing frustration and increasing time on site.
- Increased Engagement: Encourages users to re-engage with your content, potentially leading to more comments, shares, and conversions.
- Reduced Bounce Rate: By offering a quick path back to interesting content, you can keep visitors on your site longer, lowering your bounce rate.
- Enhanced Content Discovery: Users might remember the topic but not the exact title. A “recently viewed” list helps them rediscover that content.
Methods for Displaying Last Visited Posts
There are several ways to implement this feature in WordPress, each with its pros and cons. We’ll explore the following methods:
- Using Plugins (Easiest)
- Using Cookies (Intermediate)
- Using the WordPress History API (Advanced)
Method 1: Using Plugins (Easiest)
This is the simplest and recommended approach for beginners. Numerous plugins are available in the WordPress repository that handle the complexities of tracking and displaying recently viewed posts.
Recommended Plugins
Several plugins excel at this task. Some popular choices include:
- Recently Viewed Posts
- WordPress Popular Posts
- Display Posts – Shortcode
- YARPP (Yet Another Related Posts Plugin) – Can also be used to show recently viewed posts.
For this guide, we will focus on “Recently Viewed Posts” as it is specifically designed for this purpose and is easy to configure.
Step-by-Step Guide: Using the “Recently Viewed Posts” Plugin
1. **Install the Plugin:**
* Log in to your WordPress dashboard.
* Navigate to Plugins > Add New.
* Search for “Recently Viewed Posts.”
* Click “Install Now” next to the plugin.
* After installation, click “Activate.”
2. **Configure the Plugin (if necessary):**
* Some plugins offer extensive configuration options. The “Recently Viewed Posts” plugin keeps it simple. After activating, you might find a settings page under the “Settings” menu, or the options might be directly within a widget.
* Common settings might include:
* Number of posts to display.
* Displaying the post thumbnail.
* Excluding specific categories or posts.
* Customizing the title (e.g., “Recently Viewed,” “Your Recent Reads”).
3. **Display the Recently Viewed Posts:**
* **Using a Widget:** This is the most common and straightforward method.
* Go to Appearance > Widgets.
* Find the “Recently Viewed Posts” widget in the list of available widgets.
* Drag and drop the widget to your desired sidebar or widget area.
* Configure the widget options (title, number of posts, etc.).
* Click “Save.”
* **Using a Shortcode:** Some plugins offer a shortcode that can be embedded within a page or post. Check the plugin’s documentation for the shortcode. It might look something like `[recently_viewed_posts]`
* Edit the page or post where you want to display the recent posts.
* Add a Shortcode block (in the Gutenberg editor).
* Enter the shortcode provided by the plugin.
* Publish or update the page/post.
4. **Test and Customize:**
* Visit your website and browse a few posts.
* Check if the recently viewed posts are displayed correctly in the widget or shortcode area.
* Adjust the plugin settings or widget configuration to fine-tune the appearance and functionality.
Pros of Using Plugins
- Easy to install and configure.
- Requires no coding knowledge.
- Offers various customization options.
- Regularly updated by developers.
Cons of Using Plugins
- Can potentially slow down your website if the plugin is poorly coded.
- May conflict with other plugins.
- Limited control over the implementation compared to custom coding.
Method 2: Using Cookies (Intermediate)
This method involves using cookies to track which posts a user has visited. This requires adding custom code to your theme’s `functions.php` file or using a code snippets plugin.
Step-by-Step Guide: Using Cookies
1. **Access Your Theme’s `functions.php` File:**
* Log in to your WordPress dashboard.
* Go to Appearance > Theme File Editor. **(Caution: Editing theme files directly can break your site. Back up your theme or use a child theme before proceeding. Consider using a code snippets plugin instead.)**
* Select your theme (or child theme) from the dropdown menu.
* Locate the `functions.php` file.
2. **Add the Following Code to `functions.php`:**
“`php
Recently Viewed Posts
‘;
echo ‘
- ‘;
- ‘ . get_the_title() . ‘
- No posts viewed yet.
$args = array(
‘post_type’ => ‘post’,
‘post__in’ => $post_ids,
‘orderby’ => ‘post__in’, // Maintain the order from the cookie
‘posts_per_page’ => -1, // Display all posts
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo ‘
‘;
}
wp_reset_postdata();
} else {
echo ‘
‘;
}
echo ‘
‘;
}
}
}
// Function to create a shortcode to display recently viewed posts
function recently_viewed_posts_shortcode() {
ob_start(); // Start output buffering
display_recently_viewed_posts();
return ob_get_clean(); // Return the buffered output
}
add_shortcode( ‘recently_viewed’, ‘recently_viewed_posts_shortcode’ );
?>
“`
3. **Explanation of the Code:**
* `track_recently_viewed_posts()`: This function runs on the `wp_head` action. It checks if the current page is a single post. If so, it retrieves the post ID, retrieves the existing `recently_viewed_posts` cookie (if it exists), adds the current post ID to the cookie (removing duplicates and limiting the number of stored IDs to 5), and then sets the cookie to expire in 30 days.
* `display_recently_viewed_posts()`: This function retrieves the `recently_viewed_posts` cookie. If the cookie exists and contains post IDs, it creates a WordPress query to fetch those posts. It then loops through the posts and displays them in an unordered list with links to their respective permalinks. If no posts are found, it displays “No posts viewed yet.”
* `recently_viewed_posts_shortcode()`: This function creates a shortcode called `recently_viewed`. When this shortcode is used in a post or page, it calls the `display_recently_viewed_posts()` function to display the list of recently viewed posts. Output buffering is used to capture the output of the function and return it as a string.
4. **Insert the Recently Viewed Posts:**
* **Using the Shortcode:** The code above defines a shortcode `[recently_viewed]`. You can now insert this shortcode into any page or post where you want to display the recently viewed posts. Add a shortcode block in Gutenberg and enter `[recently_viewed]`.
* **Directly in Theme Files (Not Recommended):** You can call `display_recently_viewed_posts()` directly in your theme files (e.g., `sidebar.php`). **However, this is generally not recommended as it tightly couples the functionality to your theme.** Use a child theme if you attempt this.
* Open the `sidebar.php` file (or the file where you want to display the list).
* Add the following code: ``
5. **Test and Customize:**
* Visit your website and browse a few posts.
* Check if the recently viewed posts are displayed correctly in the shortcode area or the directly edited theme file.
* You can customize the HTML output in the `display_recently_viewed_posts()` function to adjust the appearance.
Pros of Using Cookies
- More control over the implementation compared to plugins.
- Lightweight and efficient.
Cons of Using Cookies
- Requires coding knowledge.
- Can be affected by browser privacy settings (users can disable cookies).
- Requires careful coding to avoid security vulnerabilities.
- May require adjustments for GDPR compliance (depending on your region and specific implementation).
Method 3: Using the WordPress History API (Advanced)
This method leverages the browser’s History API and local storage to track and display recently viewed posts. This approach offers a more modern and potentially more performant solution but requires advanced JavaScript and PHP skills. This is an extremely complex method best left to experienced developers. A complete, working example is beyond the scope of this beginner’s guide. The below outlines the general steps.
General Steps (Outline Only)
1. **JavaScript Implementation:**
* Use JavaScript to listen for page changes using the History API (`window.history.pushState`).
* When a user navigates to a post, store the post ID and title in local storage (`localStorage`).
* Limit the number of stored posts to prevent excessive data storage.
2. **PHP Implementation:**
* Create a shortcode or a function to retrieve the post IDs from local storage (passed via AJAX or a hidden input field).
* Use a WordPress query to fetch the corresponding posts based on the IDs.
* Display the posts in a formatted list.
3. **AJAX Handling:**
* Use AJAX to periodically update the recently viewed posts on the server, ensuring that the data is persisted even if the user clears their local storage.
Pros of Using the History API and Local Storage
- Potentially more performant than cookies, especially for large websites.
- More control over data storage and privacy.
- Provides a more modern and flexible approach.
Cons of Using the History API and Local Storage
- Requires advanced JavaScript and PHP skills.
- More complex to implement and maintain.
- Potential security vulnerabilities if not implemented correctly.
- Data is lost if the user clears their browser’s local storage.
Conclusion
Displaying recently viewed posts can significantly enhance user experience and engagement on your WordPress website. While the plugin method is the easiest and most accessible, the cookie method offers more control. The History API method is the most advanced and requires significant technical expertise. Choose the method that best suits your skill level and website needs. Remember to always back up your website before making any code changes and test your implementation thoroughly.
- How to Create a Video Slider in WordPress (Easy Tutorial)
- How to Install WordPress in a Subdirectory (Step by Step)
- How to Limit Comment Length in WordPress (Easy Tutorial)
- How to Show a Floating Contact Form in WordPress (3 Methods)
- How to Create a BuzzFeed Like Website Using WordPress
- How to Create a Multi-Page Form in WordPress
- How to Make a Niche Review Site in WordPress Like a Pro