WordPress: Using Conditional Tags in Plug-ins
I’ve been developing a WordPress plug-in for the Holidays (more on this at a later date) and I found something interesting. When plug-ins are loaded, the conditional tags (is_home, is_page, etc.) are effectively useless because the requested URL hasn’t been parsed yet. This was a problem for me because I wanted to be able to only have the script do its magic on the home page (by checking is_front_page). I did some searching but didn’t really find anything helpful. I even looked at the definition of is_front_page in the source code, which simply confirmed that it wouldn’t return accurate results when the plug-in was loaded. I finally thought of a good way to fix this… an action hook.
I took everything that had been running when the script loaded and placed it in a function. Then added an action to run before the header was loaded (get_header). This way the function is executed after the template information has been loaded (so WordPress knows what page has been requested) but before header.php is included. Since what I was trying to do was to add a JavaScript file to the include Queue, I could have probably attached this to wp_print_scripts, but in my case it didn’t really make much of a difference.
Anyway, the most important thing I learned here was that in order to use conditional tags in a plug-in, you have to use an action hook to wait until enough information has been loaded.
Hope this is helpful to someone else!
Leave a Reply