Иногда существует необходимость изменения шаблона для разных категорий. При этом важно, чтобы учитывались родительская категория и все дочерние категории. Не всегда удобно перечислять весь перечень дочерних категорий, и хочется указать лишь одну — родительскую. И чтобы действие распространялось на все дочерние категории существует специфическая функция Post_is_in_descendant_category
Эта функция не является стандартной в WordPress и для ее работы нужно разместить следующий код в файл вашей темы functions.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?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; } } ?> |
Далее в шаблоне, где нужно указать родительскую категорию используете следующий код: Для этого существует функция
1 2 3 |
<?php if(post_is_in_descendant_category('1') ) : ?> // Какое-либо действие <?php endif; ?> |
— где (‘1′) id родительской категории.
Для всех категорий, которые являются дочерними категории с указанным id, будет применяться действие кода.
Источник: https://wpcodereminder.wordpress.com/2013/01/13/post_is_in_descendant_category/