AMIB
AMIB

Reputation: 3430

How to check if current post or category is descendant of certain category?

I'd like to know how to check if current single post or current category is child of certain category with any depth.

For example:

Cat1 > Cat2 > Cat3 > Cat4 > Post1

Check if Post1 is child of Cat1

and check if Cat4 is child of Cat1

Upvotes: 0

Views: 392

Answers (1)

AMIB
AMIB

Reputation: 3430

This function returns true in the situations above. and false otherwise.

<?php
function post_or_category_descendant_of( $category_id ) {
    if( is_category() && ( is_category( $category_id ) || cat_is_ancestor_of( $category_id, get_queried_object() ) ) ) {
        return true;

    } else if( is_single() ){

        $post_id = get_queried_object()->id;
        $post_categories = get_the_category( $post_id );

        $post_cat_ids = array();

        foreach( $post_categories as $pc ) {
            $post_cat_ids[] = $pc->cat_ID;
        }

        $args = array( 'child_of' => $category_id, 'fields' => 'ids' );
        $target_cat_ids = get_categories( $args );
        $target_cat_ids[] = $category_id;

        if( array_intersect( $post_cat_ids, $target_cat_ids ) ) {
            return true;
        } else {
            return false;
        }

    } else {
        return false;
    }
}

Upvotes: 1

Related Questions