New here? Read Greetings Earthling!

Setting Cookies In Wordpress With PHP

I bet all of you know what cookies are (especially cookie stuffing). Now I will show you the easier way to set them in Wordpress. As you are aware the setcookie function in PHP has a whole bunch of parameters. These, in Wordpress, must be setup a little differently.

As you know there are some people (*cough* MATT CUTTS *cough*) out there who install Wordpress in directories and not domains/subdomains. Why? Beats me and I don't have the time to sketch psychological profiles of self-sabotage right now. But that makes a difference in setting the cookies. Because you usually use '/' as path but if the blog uses '/blog/' you should use that instead. The '/' cookie will also work but it will be an improper Wordpress cookie as it will also be visible to the lower paths (outside the Wordpress install). This is the choice you gotta make.

The Proper Way To Cookie Wordpress

You need to issue a site_url('/') and cookie the resulting path. The path you need to set the cookie for must be this: parse_url(site_url('/'), PHP_URL_PATH) and the host must be this: parse_url(site_url('/'), PHP_URL_HOST) and the secure bool parameter must be this: !strcasecmp(parse_url(site_url('/'), PHP_URL_SCHEME), 'https').

Get The 3 Helper Functions

As you might have noticed with all my helpers, I like to use default parameters for things I don't touch 99.99% of the times. These functions follow same principle. So get the code below and make Wordpress cookies setting regardless of the installation path, a breeze.

Zone unavailable to unregistered users.
Registration is quick, painless and worth its weight in gold.

It's way easier to use these with Wordpress cookies you need to setup than the 'stock' functions.

PS: Place these in your 5ub-eLIB.php. I use these, especially in the Cookie Stuffing plugin which is on its way.

Category: Wordpress Hacks
Tagged: ,

2 Responses

  1. +fsudirectory1:2 — #44 says:

    This looks like a much cleaner way of setting cookies than with .htaccess redirects and stuff. Will have to try it soon.

  2. +Taranis1:1 — #212 says:

    You really should have done the $5 part earlier - Now I feel more obliged to use all the stuff downloaded from here :D