Using Dynamic includes with WordPress

About me: I am an everyday Joe Schmoe that enjoys spending way too much time on the internet. Internet technologies such as XHTML, PHP, CSS, and FLASH are my best friends and hobbies. They are daily learning experiences and I enjoy sharing what I learn with others.

Dynamic includes with WordPress
Did you ever see WordPress blogs that have a separate header for different categories or a different sidebar for the single.php template page? In this article, I am going to show you a couple of different ways to achieve this functionality. You can use these simple snippets to add a custom header or even a secondary sidebar for each WordPress category. First for the simple header snippet, in your index.php page, change your normal header to this:

<?php if (is_category('wordpress')) {
get_header('wordpress');
} else {
get_header();
} ?>

The snippet above will tell WordPress that a visitor in your “wordpress” category. WordPress will then display a file called header-wordpress.php. If it does not exist WordPress will display your default header file. The next snippet will look for sidebar-wordpress.php to replace the default file if the category is wordpress.To get a “special” sidebar for this category, you only need to do is add the following code:

<?php if (is_category('wordpress')) {
get_sidebar('wordpress');
} else {
get_sidebar();
} ?>

You can do the same with your footer file. Just remember to change the hook from get_sidebar(); to get_footer();.

Another way to display a separate sidebar based on visitor location is to simply create a new file called sidebar2.php, sidebar_single.php or something easy for you to remember. This particular theme has a sidebar2.php strictly setup for the single.php template. Clear as mud? Basically, I did not want the long sidebar that my default index.php utilizes to show up on a post with a short page. Simple, huh?

Replace the sidebar hook <?php get_sidebar(); ?> on your single.php with your include <?php include ('sidebar2.php'); ?>.

My new sidebar2.php does not use widgets but I still use the same class style tags to stay with the theme.

<div class="widget">
<h4><?php _e('Pages',''); ?></h4>
<ul>
<?php wp_list_pages('title_li=' ); ?>
</ul>
</div>

I hope you found this useful. Coding is poetry in motion.

Z

Tags: , ,

The Comments

  1. WP Themes posted on April 8, 2010 | Permalink

    Nice dispatch and this fill someone in on helped me alot in my college assignement. Say thank you you for your information.

Register!


That's it - back to the top of page!

Recent Posts

POPULAR POSTS!