Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Jose Morales-Mendizabal
Jose Morales-Mendizabal
19,175 Points

Setting Cookies in a custom Wordpress Theme

I have developed a custom Wordpress theme, and I would like to add a Cookie that tracks first time visitors to the blog landing page and if they are a firs time blog visitor a modal window would come up giving users some information about the blog.

I found a snippet of code on StackOverflow that tracks first time visitors, and re-directs them to a different page (I would change this, of course)

<?php
if ($_COOKIE['iwashere'] != "yes") { 

  setcookie("iwashere", "yes", time()+315360000);  
  header("Location: http://example.com/index-first-time-visitor.php"); 

}
?>

Now how do I go about implementing my idea? Should I include the cookie script in functions.php and use an action to load the JS required for the modal only when the user is visiting for the first time? Suggest something different? Thanks!

2 Answers

Zac Gordon
STAFF
Zac Gordon
Treehouse Guest Teacher

You can enqueue this from your functions.php. I'd check to make sure they're on the right template and the cookie doesn't already exist.

There is a good argument to be made as to whether this technically should be added as a plugin versus the theme, but I assume this is a one off project and not a theme you're looking to share.

Jose Morales-Mendizabal
Jose Morales-Mendizabal
19,175 Points

Yeah, the theme I built is only for the company I work for, no one else will use it. Thanks for the answer, Zac!

missgeekbunny
missgeekbunny
37,033 Points

Please please please do not put this in a theme. The functionality you are talking about is just that. It's functionality and it belongs in a plugin. Look at the plugin basics to get you started on that.