Show a list of recently viewed posts to a user

This plugin may fulfill your requirements.

http://wordpress.org/extend/plugins/recently-viewed-posts

Usage

get_recently_viewed_posts( $max_shown = 10 ) returns a string of li’s.
recently_viewed_posts( $max_shown = 10 ) prints a div

If you are interested in learning how to develop this functionality yourself, download the plugin and see the source files. WordPress is Open Source!

Update:

The above plugin did not work. The following approach will help to
get the recently viewed video ids.

<?php        
/*
 * Plugin Name: WPSE_63266_Recently_Viewed
 */
function wpse_63266_update_recently_viewed(){

    /**
     *  If is admin or isn't single, then return.
     *  To get only singular video posts use; if(!is_singular('videos')) return;
     */
    if(is_admin() || !is_single()) return;

    global $post;

    // Get the current post id.
    $current_post_id = get_the_ID();

    if(is_user_logged_in()){

        // Store recently viewed post ids in user meta.
        $recenty_viewed = get_user_meta(get_current_user_id(), 'recently_viewed', true);
        if( '' == $recenty_viewed ){
            $recenty_viewed = array();            
        }

        // Prepend id to the beginning of recently viewed id array.(http://php.net/manual/en/function.array-unshift.php)
        array_unshift($recenty_viewed, $current_post_id);        

        // Keep the recently viewed items at 5. (http://www.php.net/manual/en/function.array-slice.php)
        $recenty_viewed = array_slice($recenty_viewed, 0, 5); // Extract a slice of the array

        // Update the user meta with new value.
        update_user_meta(get_current_user_id(), 'recently_viewed', $recenty_viewed);

    } else {

    /**
     * For non-logged in users you can use the same procedure as above
     * using get_option() and update_option()
     */

    }
}
add_action('wp_footer', 'wpse_63266_update_recently_viewed');

function wpse_63266_show_recently_viewed(){

    $recenty_viewed = get_user_meta(get_current_user_id(), 'recently_viewed', true);
    echo '<pre>'; print_r($recenty_viewed); echo '</pre>';
}
add_action('wpse_63266_recently_viewed', 'wpse_63266_show_recently_viewed');
?>

do action() in your template to see the change of array values (video ids) while you are browsing through the posts.

do_action('wpse_63266_recently_viewed');

Leave a Comment