Conditional Tags: Page Templates
January 15th, 2010
What’s the old saying, “Learn something new every day?” Working on customizing a theme for a client today, I was running into a bit of a tricky situation. The theme developer, for what ever reason, was using some php conditionals in the header to check to see if a page was the home page or not, and depending on the condition, he was inserting the CSS directly into the header and setting a background image on the container. Now why they didn’t simply use the same conditional and set a class and then use different background images in the style sheet is beyond me, but time and budget didn’t dictate that I rewrite the whole thing to do it properly. So my first stab at resolving the issue was to use the conditional tag that I knew about, is_page();. I also knew that you could specify which page by ID or slug. However, in my situation, I had created several new page templates which didn’t need the background image, as it had a repeating strip for a faux column on a third sidebar. So I took a stab at the docs again on conditional tags, and lo and behold, since WP 2.5, you can now check if it is a page template with, wait for it, if(is_page_template()). Not only that, but you can specify a template by the file name, ie, if(is_page_template('archives.php')). Wait, it gets better! You can also do an array of page templates, if(is_page_template(array('archives.php','about.php','contact.php'))). How awesome is that?
In my scenario, I simply wanted to check if it was any template besides the default template, so I was able to use if(!is_page_template('page.php')) and boom!, none of my page templates would get the faux column background.
Thinking about it, now I’m glad the theme designer took the backwards approach to the background image so that I could learn a new trick for the toolbox.
Popularity: 24% [?]
