Wednesday, July 5, 2017

How to Show Content to Users Only Once in WordPress Using Cookies

The following is external content provided as a free resource for blog readers.

Say you want to show visitors some content the first time they visit your homepage. Maybe you’ve got a WordPress site that shows some “about us” text at the top of the homepage and then your latest posts below that. Do visitors really want to see that same static text every time they visit? Probably not.

There’s already a great plugin that can do this, it’s called What Would Seth Godin Do and is available for free from WordPress.org. With that, you can show some HTML content to users and there are a bunch of configurable settings. This post instead deals with how to do it directly in your theme, so you can take advantage of PHP, WordPress loops, and other fun stuff.

We’ll do this by setting a cookie via PHP, checking if that cookie exists, and if it does, doing something specific.

Firstly, in your header.php file, add the following at the very top, before the <!DOCTYPE html> declaration, and don’t leave any spaces between the closing PHP tag and that DOCTYPE tag:

<?php if (is_front_page()) {
if (!isset($_COOKIE["notacarrot"])) {
setcookie("notacarrot", "beentheredonethat", time()+31500000);
}
} ?>

In that code, the first line is saying “If we’re on the front page…”

The second line checks to see if our cookie is set yet, and if it isn’t, we set the cookie on the third line. That 31500000 states that the cookie should remain on the visitor’s machine for that many seconds, which is about half a day shy of a year.

We’ve also named our cookie notacarrot and given it a value of beentheredonethat.

If you wanted the code to execute on every page, change it to:

<?php if (!isset($_COOKIE["notacarrot"])) {
setcookie("notacarrot", "beentheredonethat", time()+31500000);
} ?>

Next, we’ll setup where you want the conditional statement to read, “If this cookie does not exist, show this content.”

<?php if ($_COOKIE["notacarrot"] == "beentheredonethat") { ?>
// DO SOMETHING
<?php } ?>

This says, “if the cookie called notacarrot has a value of beentheredonethat, do something”.

The “DO SOMETHING” bit is up to you. ?

0 comments:

Post a Comment