Проверьте, находится ли сообщение в какой-либо дочерней категории родительской категории


На сайте, который я разрабатываю, у меня следующая структура категорий:

* movies (parent)
    * thriller (child)
    * comedy (child)
    * drama (child)

Текущий пост находится в категории комедия. Функция has_term со следующими параметрами возвращает значение true:

has_term( 'comedy', 'category' )

Но та же функция со следующими параметрами возвращает false:

has_term( 'movies', 'category' )

Мой вопрос в том, существует ли основная функция для проверки, находится ли текущая запись в какой-либо дочерней категории определенной родительской категории? Если нет, как я могу проверить это?

Заранее благодарю

Author: leemon, 2014-07-21

2 answers

Добавьте следующее в свою тему functions.php :

/**
 * Tests if any of a post's assigned categories are descendants of target categories
 *
 * @param int|array $cats The target categories. Integer ID or array of integer IDs
 * @param int|object $_post The post. Omit to test the current post in the Loop or main query
 * @return bool True if at least 1 of the post's categories is a descendant of any of the target categories
 * @see get_term_by() You can get a category by name or slug, then pass ID to this function
 * @uses get_term_children() Passes $cats
 * @uses in_category() Passes $_post (can be empty)
 * @version 2.7
 * @link http://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category
 */
if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, 'category' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}

Используйте функцию, чтобы проверить идентификатор родительской категории, а не имя или название. Т.е. Если идентификатор категории "фильмы" равен 50:

if ( post_is_in_descendant_category( 50 ) ) {
    // do something
}

Если вы не знаете идентификатор категории "фильмы", вы можете получить идентификатор с помощью get_term_by() и передать его в post_is_in_descendant_category():

$category_to_check = get_term_by( 'name', 'movies', 'category' );

if ( post_is_in_descendant_category( $category_to_check->term_id ) ) {
    // do something
}
 16
Author: Gabriel, 2014-07-21 21:33:17

Если вы хотите любую глубину вложенности , используйте get_posts.

/**
 * Checks if the post is in one of the categories or any child category. 
 * 
 * @param  int|string|array $category_ids (Single category id) or (comma separated string or array of category ids).
 * @param  int              $post_id      Post ID to check. Default to `get_the_ID()`.
 * @return bool true, iff post is in any category or child category.
 */
function is_post_in_category( $category_ids, $post_id = null ) {
    $args = array(
        'include'  => $post_id ?? get_the_ID(),
        'category' => $category_ids,
        'fields'   => 'ids',
    );
    return 0 < count( get_posts( $args ) );
}

Вы можете расширить эту функцию многими способами. Возможно, передать массив идентификаторов сообщений и отфильтровать некоторые или разрешить уточнение запроса.

 0
Author: Josef Wittmann, 2020-09-22 08:51:23