Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Display users last visited post WordPress

I'm allowing logged in users to follow a story with multiple paths, meaning when they log in I need to give them the option to read from where they last read.

To do this I'm using the following code within the single-story.php to store the time and ID of the user who last visited the post.


<?php
if (get_post_type( $post->ID ) == 'story' )
add_post_meta( $post->ID, 'viewing_history', ''.current_time('mysql').', '.$viewing_history_id.'');
?>


The issue I'm having is retrieving this last post, so far I have the following


<?php
$args = array(
'post_type' => 'story',
'posts_per_page' => -1,
'meta_key' => 'viewing_history',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'viewing_history',
'value' => array( $viewing_history_id ),
),
),
);
query_posts( $args ); ?>


The variable $viewing_history_id stores the current logged in users ID.

I got the code to display results but I need some more control.

I need the above code adapting so when a user logs in and the query is ran it's organised by the time saved within the meta_value then checks that the value saved after the date matches the logged in user ID which was stored with the variable. I feel like the codes almost their, just needs a little hand.

The end goal should mean that each user logged in can retrieve the last post they visited.

For reference I've attached what the row looks like when added to the database, nothing out of the ordinary I don't think.

Answers (2)

2015-01-13

Dbranes answers:

Why don't you use the user meta to store the last visited story for each user?

With something like:

update_user_meta( $user_id, 'last_visited_story_id', $post_id );


where <em>$post_id</em> is the last visited story ID.

Then you can fetch it with for example:


$pid = get_user_meta( $user_id, 'last_visited_story_id', true );

if( ! empty( $pid ) ) {
$lastpost = get_post( $pid );
}



PS: Don't use <em>query_posts()</em>, it's not recommended. Use <em>WP_Query()</em> or <em>get_posts()</em> instead.


Dbranes comments:

Why don't you use the user meta to store the last visited story for each user?

With something like:

update_user_meta( $user_id, 'last_visited_story_id', $post_id );


where $post_id is the last visited story ID.

2015-01-13

Bob answers:

Yes I think Dbranes is right. You should store value in user meta.

However if you prefer to go with Cookie based solution then this plugin might be helpful.

[[LINK href="https://wordpress.org/plugins/last-viewed-posts/"]]https://wordpress.org/plugins/last-viewed-posts/[[/LINK]]

Of course you need to change a code slightly to suit it with your need. May be you need to add one condition to check for your custom post type(story).