Show a user their recently viewed posts

I am working on a project that showcases a number of products, so I’d like to add a “recently viewed product” selection that keeps track of the last 5 or so viewed products or posts.

I saw this plugin but its 2 years old and as of now doesn’t look to be supported.

Read More

Any ideas?

Related posts

Leave a Reply

1 comment

  1. You can add a timestamp to your post meta each time a product is viewed, then query the five most recently viewed products.

    Assuming you are using a custom post type named ‘product’, add the following inside the loop of your single-product.php template file:

    <?php 
    if (get_post_type( $post->ID ) == 'product' )
        update_post_meta( $post->ID, '_last_viewed', current_time('mysql') );
    ?>
    

    To display the five most recently viewed products:

    <?php
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 5,
        'meta_key' => '_last_viewed',
        'orderby' => 'meta_value',
        'order' => 'DESC'
    );
    query_posts( $args ); ?>
    <?php if( have_posts() ) : ?>
        <?php while( have_posts() ) : the_post(); ?>
            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <?php endwhile; ?>
    <?php endif; ?>
    <?php wp_reset_query(); ?>