How to Show Content to Users Only Once – WordPress Cookies

How to Show Content to Users Only Once – WordPress Cookies

Astra WordPress Theme

By default, WordPress uses cookies to manage logged-in user sessions and authentication. It also uses cookies to remember a user’s name and email address if they fill out a comment form. However, many WordPress plugins on your website may also set their own cookies.

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 WordPress 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 set up 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 WordPress cookie called notacarrot has a value of beentheredonethat, do something”.

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

You might also like to read:

Written by
Suresh Patel
Join the discussion

Let’s get social

Web design blog for professionals with topics focusing on useful design techniques, design best practices and design inspiration. Subscribe for updates!

Subscribe To Our Blog For All The Latest & Greatest Freebies!

Following our blog is a great way to make sure that you are up to date on the latest and greatest Freebies and WordPress news.

We don't spam and your information will never be shared.