How to tell Wordpress category page to call specific sidebar
I am trying to pull in a styled sidebar specific to the category. I have the following code which works, but it is pulling in BOTH my new sidebar and the default. What am I doing wro开发者_开发技巧ng here?
From category.php
<?php get_sidebar();
if ( in_category('39') ) {
include(TEMPLATEPATH . '/sidebar2.php');
} else {
include(TEMPLATEPATH . '/sidebar.php');
}
?>
<?php get_footer(); ?>
Because you're calling sidebar twice; do this:
<?php
if ( in_category('39') ) {
include(TEMPLATEPATH . '/sidebar2.php');
} else {
include(TEMPLATEPATH . '/sidebar.php');
}
?>
There is a slight problem with the code being provided to you. But as Eimantas suggested, you could simply make a new file called category-39.php which will accomplish the job perfectly, if though for some reason you are still wanting to continue using your category.php file, then here is what you would need to do:
if ( is_category('39') ) {
get_sidebar('2');
} else {
get_sidebar();
}
?>
<?php get_footer(); ?>
The difference between this and the code that you posted is that I have removed
<?php get_sidebar(); ?>
Additionally I have changed in_category to is_category. The reason for this is because when looking at the category page itself using is_category will change on the category list, whereas in_category only looks at the current post and therefore will not change according except when looking at the single.php page.
Example: in_category will change the sidebar for the following url www.mysite.com/category/stuff/myfirstpost But it will not change the sidebar for this url www.mysite.com/category/stuff Simply using is_category will fix this problem.
The next thing would be using
get_sidebar('2');
and
get_sidebar();
get_sidebar(); will run the appropriate wordpress functions related to the sidebar in addition to including sidebar.php. get_sidebar('2'); on the other hand will run all the appropriate wordpresss functions related to the sidebar while also loading sidebar-2.php.
Hope this helps,
Remove this from your code:
get_sidebar();
otherwise you call this file "sidebar.php" twice...
if you look into wp documentation http://codex.wordpress.org/Function_Reference/get_sidebar
you can do it like that:
<?php
if ( in_category('39') ) :
get_sidebar('two'); //this will include sidebar-two.php
else :
get_sidebar();
endif;
?>
You should create separate template named category-39.php and do common design stuff. WP itself will notice that it should apply this template to category with id=39. No need for if else statements.
精彩评论