简体   繁体   中英

WordPress posts in multiple categories - different sidebar depending on category

  1. I'm not sure of the terminology, so please bear with me!

I've found code to display different content in the sidebar dependent on the category the post is in. I have this in my sidebar.php (alienship theme):

if ( in_category('32') ) {
echo "<h3>32</h3>";
} elseif ( in_category('33') ) {
 echo "<h3>33</h3>";
} elseif ( in_category('34') ) {
 echo "<h3>34</h3>";
} elseif ( in_category('35') ) {
 echo "<h3>35</h3>";
} elseif ( in_category('36') ) {
 echo "<h3>36</h3>";
} elseif ( in_category('37') ) {
 echo "<h3>37</h3>";
} else {
 echo "<h3>everyone else</h3>";
}

This works fine until a post is in multiple categories eg if a post is in categories 32 and 36 the text displayed is "32" when I'm looking at /?cat=32 AND /?cat=36. And if I then view the post itself the problem is the same.

What I want to achieve is:

  • Post in two categories - 32 and 36

  • if i'm viewing the post via category 32 "32" should be displayed

  • if i'm viewing the post via category 36 "36" should be displayed

Is this possible? Any help much appreciated!

If you are in a category archive, you will have the category available via the query var.

$cat = get_category(get_query_var('cat'))->cat_ID;

https://codex.wordpress.org/Function_Reference/get_category

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM