Wordpress - Get Current Category Parents

2019-01-26 12:51发布

问题:

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!

回答1:

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


回答2:

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



回答3:

Check out the reference page for get_category_parents, you are asking for links when you set the second parameter to TRUE.

You should be doing:

    get_category_parents($cat, FALSE, ', '));

I also recommend not using spaces as separators, since you will probably need to trim those spaces later.