Jump to Sidebar Content | Jump to Main Page Content

Begin site navigation:
End site navigation.
Begin left menu:


End of left menu.
Begin main content:

WordPress Tips & Tricks: Dynamic Conditionals for Sub-Pages

Sunday, February 12, 2012 2:51 pm

If you build CMS-style websites in WordPress, you’re familiar with template tags and PHP. My favorites are Conditional Tags, and every custom theme I create involves heavy use of them. Conditional Tags are great for displaying targeted content on certain pages, such as a different background on a home page or topic-based widgets in sidebars.

Here’s an example of simple conditionals:

Conditionals on sub-pages are a little trickier: we need to identify the parent page:

post_parent == '28') {
// the page is "About", or the ID of the parent page is 28
} elseif is_page('Work') || $post->post_parent == '42') {
} elseif (is_page()) {
} else {
} ?>

Most conditionals (and many $wpdb queries) require the page ID to check for the page parent. But what if you don’t know the parent ID? The Reveal IDs plugin should be part of your standard WordPress distribution. Sometimes, though, you will want to call it from the database.

Here’s a simple query to identify IDs of the current and parent pages:

$myparent = $post->post_parent;
$parent_title = get_the_title($post->post_parent);
echo "Post ID = ". $the_post_id . " Parent ID = " . $myparent . " Parent Name = " . $parent_title;

Now, if you’re building a theme and you know the content, using IDs for your conditionals may work fine. However there are cases where that may be less than ideal. If you’re themeing in a development environment, the parent ID typically won’t match the parent ID when the theme is used in production. That can cause headaches when you roll out changes in the future: you’ll need to know the IDs of both parent pages and swap between the two. Multiple navigation menus, single-page parallax-style websites, and other scenarios can be problematic when specifying the parent ID. Using the name of the parent page instead of ID solves a lot of these headaches.

Make it dynamic:

$parent_post_title1 = 'About';
$parent_post_title2 = ' Work ';
if ($parent_title = = $parent_post_title1) {
// do something here for sub-pages in the About section
} elseif ($parent_title = = $parent_post_title2) {
// do something different for sub-pages in the Work section
} ?>


Comments are closed.

End of main content.