Jan 8 Wordpress: Style Top Level Pages Differently
Recently, I needed to figure out how to apply different styles to the top level pages on a Wordpress site than those applied to child pages. After a little digging, I figured out a fairly easy way to determine which is which.
Granted, I could easily create a custom page template and assign it to each of my top level pages, but that would require anyone creating new pages to recognize whether or not the custom template is supposed to be applied, and that change would have to be made any time a page is moved.
Instead, I wrote some simple functions to check whether or not a page is a child page or not. I then use that function to assign a specific class to the elements that need to be styled differently.
If you copy and paste the following functions into the functions.php file for the theme you’re using.
function has_children() {
global $post;
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
return ($children) ? true : false;
}
function is_child() {
global $post;
return ($post->post_parent) ? true : false;
}
The first function is developed to check whether or not a page has any children. If it does, it returns true; if not, it returns false. You would use that function wherever you want to display something different for pages that have subpages and for pages that don’t.
The second function checks to see if the page has a parent. If it’s a subpage of some other page on your site; the function will return true. If it’s not a subpage (if it’s a top-level page), the function will return false. The second function is really the one we’ll be using for the purposes of this post, but I wanted to include the first function in the event that you find a use for it.
To use the second function, you might do something similar to the following.
<h1 class="<?php echo (is_child()) ? 'child' : 'topLevel'; ?>"><?php the_title(); ?></h1>
The code example above will check to see whether or not this is a top-level page. If it is, we assign a class of “topLevel” to the h1 tag. If it’s not a top-level page, we assign a class of “child” to the h1 tag. You can use this function on a simple item like an h1 tag as shown above, you could use it to assign a class to the entire post or you could even use it (or the other function I included above) to add extra content based on whether or not the page is a top-level page, if it is a child page, if it has children or not.
Related posts:






