Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress - Get Current Category Parents

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!

like image 579
Matrym Avatar asked Jun 25 '10 01:06

Matrym


2 Answers

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':

cat_is_ancestor_of(get_cat_id('blog'), get_query_var('cat'))
like image 199
Richard M Avatar answered Sep 18 '22 18:09

Richard M


First, you have to get current category's id:

$category_id = get_query_var('cat');

Then you can make a database query to see it has a parent or not:

$parent = $wpdb->get_var("SELECT parent FROM ".$wpdb->prefix."term_taxonomy WHERE term_id = $category_id");

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:

<?php if ($parent > 0 ) : ?>
// do something
<?php endif; ?>

You can use $parent however you want;

$parent_link = get_category_link( $parent );
$parent_name = get_cat_name( $parent );
// etc.

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

like image 33
gasoved Avatar answered Sep 20 '22 18:09

gasoved