In category.php, how would I test against a category having a parent category?
If the parent category is A, and the sub-category is B, and the user loads the URL for category B, I would like to be able to test if it has parent A, and run code if it does.
I've found the get_category_parents tag, but it seems to return a link list rather than an array:
get_category_parents($cat, TRUE, ', '));
Even if I got the array, I'm not sure what the php function is to test against it (php noob).
Thanks!
First, you have to get current category's id:
Then you can make a database query to see it has a parent or not:
If it has one, $parent will contain one-level-above parent's id and naturally it's value should be greater than 0, so you can check this like below:
You can use $parent however you want;
If you want to see that there is more high-level parent's, you can do the same things(db query) with parent's id or even write a recursive function that go to until top level. As i saw in the source code, built-in get_category_parents() function do it like that.
HTH
You can use the
cat_is_ancestor_of
function to check if a category is a child of another category. For example to check if the current category is a child of a category named 'blog':Check out the reference page for
get_category_parents
, you are asking for links when you set the second parameter toTRUE
.You should be doing:
I also recommend not using spaces as separators, since you will probably need to trim those spaces later.