The power of if / else statement in WordPress
The requests mentioned above, can be implemented with a smart if /else statement solution:
<!--sidebar conditional navigation sidebar--> <?php if (is_page_template('page-services.php') ) { ?> <!--than include the services specific navigation--> <?php include("side-nav-services.php") ;?> <?php } elseif ( is_home(7) || is_single() || is_category() ) { ?> <!--if not, include the blog navigation for blog section--> <?php include("side-nav-blog.php") ;?> <?php } else { ?> <!--if not anything from above, include the generic page navigation for the rest of the pages--> <?php include("side-nav-pages.php") ;?> <?php } ?>
Code explained:
First statement
The first piece of code tells us if we have a page template page-services.php, than it should include the navigation for that part. The side-nav-services.php contains:
<div id="side-nav" class="side-nav-services"> <ul> <h3>Services</h3> <!--the code from below will display sub-pages of services page with the id of 4--> <?php wp_list_pages('child_of=4&title_li&depth=1'); ?> </ul> <ul> <!--this code will display the popular links, manageable from wordpress backend--> <?php get_links(); ?> </ul> </div>
Second statement
The second portion of code, includes instead, the blog links from the file side-nav-blog.php for blog index, categories and single page. Here, the sidebar contains:
<div id="side-nav" class="side-nav-blog"> <ul><h3>Latest Posts</h3> <li><a href="<?php bloginfo('url') ;?>/health-wisdom">Health Wisdom Blog</a> <ul> <?php wp_get_archives('title_li=&type=postbypost&limit=10'); ?> </ul> </li> </ul> <ul><h3>Categories</h3> <li><a href="<?php bloginfo('url') ;?>/health-wisdom">Health Wisdom Blog</a> <ul> <?php wp_list_categories('&title_li='); ?> </ul> </li> </ul> <?php if ( function_exists('wp_tag_cloud') ) : ?> <ul><h3>Popular Tags</h3> <?php wp_tag_cloud('smallest=8&largest=22'); ?> </ul> <?php endif; ?> </div>
Third statement
The last logic, tells that if there is no blog or services section it should load the normal navigation. side-nav-pages.php contains:
<div id="side-nav" class="side-nav-pages"> <ul> <?php get_links(); ?> </ul> </div>
Conclusion
While the same result could have been accomplished with other method, by creating page templates for each sidebar, that method is more clumsy and the site harder to maintain.
If / else statements, can be of tremendous help in accomplishing tasks with WordPress (or other CMS applications) and can be used for displaying categories in a certain way or output code only in desired areas of the website.
This programming logic, also allows the developer code faster and the websites will be easier to maintain.