This is driving me crazy, and I have tried a variety of different things. Essentially, the desired effect is to target two different categories in WordPress using the built in in_category
function.
Here is my code as it stands currently:
if(in_category( array("Snacks", "Other Nuts") )) :
//do something
endif;
This will work with the category Snacks
but not with the category Other Nuts
. When I replace Other Nuts
with another category name, like Confections
, it works perfectly.
I am assuming this has something to do with the space in the category name Other Nuts
. Though, I have tried using it’s category ID and category slug to no avail.
Any idea what’s going on here??
Figured it out.
Let’s say you have two categories, one is a parent of the other, like so:
If you make a post in WordPress and categorize it in
Almonds
and run a simple loop likeYou would get the output of the
Almonds
post that belongs to theOther Nuts
parent category that’s categorized inAlmonds
. Now, if you were to run this loop instead:You would get nothing. The reason is because you have only categorized the post in
Almonds
and not also inOther Nuts
. WordPress doesn’t make the connection between the parent and child category in this case. Being categorized in the child doesn’t also categorize it in the parent.Essentially, this should check all current category IDs for the post against all of the ID’s that you’re expecting, then check all of the parent category IDs against what you’re expecting. You could compare the category names, instead, with a slight variation to this code.
Step 1: Put this in your functions.php file:
Step 2: Put this psuedo-code into whatever category template(s) you’re building: