Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've been trying to look for a way to create a loop in my website and show posts being read/watched but have not found anything.

The only way I can accomplish this would be to create a new meta key (custom field) and assign timestamp as value, that way I can create a loop and use its value to list posts that are being watched within a time range, say 5 minutes.

The issue is that I am very very new to wordpress and i dont know how to do this T_T

share|improve this question

1 Answer 1

A very simplistic method of achieving this would be as follows;

add_action('template_redirect', 'recently_read');
function recently_read(){

    global $post;

    //only run this function for the posts post_type
    if ( !is_single() ) 
        return;

    //get the current time in the format of: 2013-02-22 11:55:51 
    $timestamp = current_time('mysql'); 

    //add the $timestamp variable to the meta_key for this post
    update_post_meta($post->ID, 'reading_this', $timestamp);


}

Note: The above function goes into your theme functions.php file and is hooked onto the template_redirect action which is fired just before displaying the page to the user. At this point, behind the scenes, our recently_read function will fire and add a time stamp under the key reading_this (name it to your liking). This will occur each time this or any post is viewed. If a time stamp already exists for a given post, it will then update the time stamp accordingly.

Then to retrieve a list of posts with this key you would do the following in your theme files where you want those posts to display;

$recently_read = get_posts( 
    array(
        'posts_per_page'  => 5,       //how many posts we want to show at most
        'meta_key' => 'reading_this', //get posts by our meta key
        'orderby' => 'meta_value',    //order posts by the value stored in the key
        'order' => 'DESC'             //order posts in descending order (newest to oldest)
   )
); 

foreach ($recently_read as $read) {
    echo '<a href="'. get_permalink($read->ID) . '">'. $read->post_title .'</a>';
}

The above could be improved a number of ways but this will definitely get you started.

Note: This is void of any logic that determines if the post was viewed in the last X minutes. For that you can apply your own logic to the meta_key named reading_this and manipulate the data to your liking.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.