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

Show number of new posts since last visit based on cookie WordPress

  • SOLVED

Hi guys!

This is what I want to do:

I want to display the number of new posts since the visitors last visit, by setting a cookie for each visitor, saving the date and time of the visit.

In the site menu, I have a link to a query fetching the latest posts. On this menu item I want to, if there are new posts since last visit, display the number of new posts.

If there are more than 19 new posts, it should say "20+".

Should look something like this:

<strong>LATEST (3)</strong>

or

<strong>LATEST (11)</strong>

or

<strong>LATEST (20+)</strong>

The visitor should be able to browse the site, without the cookie reseting. The cookie should only be reset (and the new post count disappear) if the user visits the "Latest posts query page".

The latest posts query page is fetched by modifying the home page query (<em>https://site.com?show=latest</em>), like this:

if(isset($_GET['show']) && $_GET['show'] == 'latest')

So, to break it down:

<strong>1.</strong> Set a cookie the first time a visitor visits the site.
<strong>2.</strong> When there are new posts since the cookie is set, count them and show the number together with the LATEST menu item.
<strong>3.</strong> Reset the cookie only when the visitor visits the LATEST page (this removes the number with the LATEST menu item).

I found this guide, which could be used as template perhaps, but modified with the count of posts instead of changing the post titles:

[[LINK href="http://premium.wpmudev.org/blog/how-to-highlight-new-content-for-returning-visitors/"]]http://premium.wpmudev.org/blog/how-to-highlight-new-content-for-returning-visitors/[[/LINK]]

For your knowledge: I'm using the built in navigation menu system in WordPress (Appearance -> Menus).

Would be great if I could style the number of posts output with css. So maybe add the number with a <span> tag around it or something.

Thanks a lot!

// Jens.

Answers (3)

2015-08-21

timDesain Nanang answers:

Hi, you can try the following code:

// Set a cookie for lastvisit with current GMT datetime in UNIX format
// http://premium.wpmudev.org/blog/how-to-highlight-new-content-for-returning-visitors/
function wpq11504_set_cookie() {
if ( is_admin() ) return;

if( !isset($_COOKIE['lastvisit'])
OR (isset($_GET['show']) && $_GET['show'] == 'latest')
){
$current = current_time( 'timestamp', 1);
// set the cookie with current datetime (UNIX format GMT), expires in 7 days
setcookie( 'lastvisit', $current, time()+60+60*24*30, COOKIEPATH, COOKIE_DOMAIN );
}
}
add_action( 'init', 'wpq11504_set_cookie' );


// count latest post after latest visit
function wpq11504_count_latest_posts() {
if ( is_admin() ) return;

if(isset($_COOKIE['lastvisit'])){
$lastvisit = $_COOKIE['lastvisit'];

$args = array(
'posts_per_page' => -1,
'post_type' => array('post'),
'ignore_sticky_posts' => 1,
'date_query' => array(
array(
'column' => 'post_date_gmt',
'after' => array(
'year' => date("Y", $lastvisit),
'month' => date("n", $lastvisit),
'day' => date("d", $lastvisit),
),
),
),
);
$wpq = new WP_Query( $args );

return $wpq->found_posts ;
}
else return;
}

//https://wpbeaches.com/adding-loginlogout-existing-menu-wordpress/
function wpq11504_navmenu($items, $args) {
$count = wpq11504_count_latest_posts();
$show_count = $count > 0 ? '<span class="latest-count">'.($count > 19 ? '20+' : $count).'</span>' : '';

if( $args->theme_location == 'utama' ) { // change menu location
$items .= '<li class="menu-item"><a href="'.home_url('?show=latest').'">Latest '.$show_count.'</span></a></li>';
return $items;
}
return $items;
}
add_filter('wp_nav_menu_items', 'wpq11504_navmenu', 10, 2);


Jens Filipsson comments:

Hey and thank you!

This seems to be a working solution, the latest item is added to the menu, but the only thing not happening is the number showing up.

Right now I'm trying it locally on MAMP, could this be a problem? Not sure if cookies works on MAMP?

// Jens.


timDesain Nanang comments:

the code should be working properly.

- if the cookie (lastvisit) is not set, then set the cookie (lastvisit) with the current time
- the number not showing up, because there is no posts after lastvisit (the current time)

put the following code for debugging:

function wpq11504_wp_footer() {
if(isset($_COOKIE['lastvisit'])){
$lastvisit = $_COOKIE['lastvisit'];
echo '<p>Cookie timestamp: '.$lastvisit.'</p>';
echo '<p>Cookie Ymd: '.date( "Y-m-d H:i:s", $lastvisit).'</p>';
}
else{
echo '<p>Cookie is not set.</p>';
}
echo '<p>Num Latest Posts: '.wpq11504_count_latest_posts().'</p>';
}
add_action('wp_footer', wpq11504_wp_footer );



or you can try change this line (current year)
'year' => date("Y", $lastvisit),
with (last year)
'year' => date("Y", $lastvisit)-1,


Jens Filipsson comments:

Ok, the cookie seems to have set:

<em>Cookie timestamp: 1440156828

Cookie Ymd: 2015-08-21 11:33:48

Num Latest Posts: 0</em>

But, when I add a new post and then visit the blog (not logged in), it doesn't update Num Latest Posts. It's still 0.


Jens Filipsson comments:

Ok! When changing Year to last year, it worked! 13 new posts. Any ideas why?


Jens Filipsson comments:

But: The cookie doesn't reset when I visit http://site.com/?show=latest.

Still says 13 posts.


Jens Filipsson comments:

Oh, wait. You only break it down to days, right? Maybe we need to break it down to at least minutes?


timDesain Nanang comments:

<blockquote>Ok! When changing Year to last year, it worked! 13 new posts. Any ideas why?</blockquote>
before:
lastvisit = <strong>2015-08-21 11:33:48</strong>
because there is no posts after the current time (it is future post)

after:
lastvisit = <strong>2014-08-21 11:33:48</strong>
there are 13 posts after this time

here is another way for debugging (on localhost):
- change the year to the original code
'year' => date("Y", $lastvisit),
- reset/ delet your cookie
- change your pc date setting to 2014-08-21 (last year)


<blockquote>But: The cookie doesn't reset when I visit http://site.com/?show=latest. </blockquote>
actually the cookie was reseted to the new value, try to open another page


Jens Filipsson comments:

But right now it only checks posts from the same day, right? I think we need to check minutes! We post many articles every day.

'year' => date("Y", $lastvisit)-1,

'month' => date("n", $lastvisit),

'day' => date("d", $lastvisit),


Jens Filipsson comments:

You're right about the cookie btw, it did update. But we need to check down to at least a minute, so that returning visitors can see if there are new articles today...


timDesain Nanang comments:

you can modified the date_query

// count latest post after latest visit
function wpq11504_count_latest_posts() {
if ( is_admin() ) return;

if(isset($_COOKIE['lastvisit'])){
$lastvisit = $_COOKIE['lastvisit'];

//modified the last visit time
$make_time = gmmktime(
date("H", $lastvisit)-5, //hour
date("i", $lastvisit)-4, //minutes
date("s", $lastvisit),
date("n", $lastvisit),
date("j", $lastvisit), //day
date("Y", $lastvisit)
);
$after_this = date("Y-m-d H:i:s", $make_time);

//https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
$args = array(
'posts_per_page' => -1,
'post_type' => array('post'),
'ignore_sticky_posts' => 1,
'date_query' => array(
array(
'column' => 'post_date_gmt',
'after' => $after_this,
),
),
);
$wpq = new WP_Query( $args );

return $wpq->found_posts ;
}
else return;
}


Jens Filipsson comments:

Thanks, worked like a charm! Have voted you the price!

2015-08-21

Andrea P answers:

Hello Jens,

the tutorial you have linked is just about the small part of the work which is setting the cookie.
there is quite a bit more work to do in order to achieve what you want, and it will require to custom code and integrate with your current files, so it's not very easy to just pass you some code here.

but most important, do you have an actual budget for this project? I am afraid that this work worth definitely more than $20..

let me know if you are willing to discuss the terms and negotiate a budget.
cheers!
Andrea


Jens Filipsson comments:

Hey Andrea,
in my head, we need to alter the title-function to instead count the ids, and then echo this number in the menu?

Something like this:

if ($publish_date > $lastvisit) {
$id_count = count($id);
}


But maybe it's more advanced than this?


Jens Filipsson comments:

(implementing code in different template files won't be a problem)


Andrea P comments:

that function is hooking the title displaying for a single post when it is into a loop.
so when it runs that code, it is minding only about 1 post, you can't count the total ids in there..

I am sorry but you'll have to plan a different strategy to achieve what you want, you can't use that function.


Jens Filipsson comments:

Of course I mean that we need some foreach statement etc. Or build it like a query.

Anyway, you can suggest me a price what you think it's worth. Then we'll see if I go with that, or if someone else decides to do it for the price suggested here.

Thanks!


Andrea P comments:

ok jens!

let wait a couple of hours and see if someone else is fine with the $20, otherwise I'll make a plan and text you a quote about this work.

cheers!
Andrea

2015-08-21

Hariprasad Vijayan answers:

Hi Jens,

Is the count based on all new post or some particular category? Is it for the same site that we worked together?

Regards,
Hariprasad


Hariprasad Vijayan comments:

Hi Jens,

Is the count based on all new post or some particular category? Is it for the same site that we worked together?

Regards,
Hariprasad


Jens Filipsson comments:

Hey Hari,
it's for the same site. Not particular category, just the normal post type "posts".