Wordpress - Get Current Category Parents

前端 未结 2 1504
既然无缘
既然无缘 2020-12-19 09:26

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

相关标签:
2条回答
  • 2020-12-19 10:12

    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

    0 讨论(0)
  • 2020-12-19 10:15

    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'))
    
    0 讨论(0)
提交回复
热议问题