wordpress检查页面是否归属特定分类函数:in_category()


【函数介绍】

in_category()函数的作用是检查当前或者指定页面是否归属于特定的分类目录,通常用于给不同的分类目录设置不同的文章模板。

【函数用法】
  1. <?php in_category( $category, $_post ) ?>

【参数说明】

$category
参数$category(必需)一个或多个目录ID (integer)、名字或者slug (string), 或者一个数组。
$_post
(混合) (可选)文章ID活文章对象. 默认为当前查询的文章对象或ID.
默认: None

【示例】

指定不同的目录文章应用不同的模板:

  1. <?php
  2. if ( in_category(1) ) {
  3. include 'single-1.php';
  4. } elseif ( in_category('seo') ) {
  5. include 'single-seo.php';
  6. } else {
  7. // Continue with normal Loop
  8. if ( have_posts() ) : while ( have_posts() ) : the_post();
  9. // ...
  10. }
  11. ?>

这里要注意的是,in_category()函数只能指定一级目录,如果该目录有子孙目录则无效。如”fruits”下还有子目录’apples’, ‘bananas’, ‘cantaloupes’, ‘guavas’,则需全部目录列出来:

  1. <?php if ( in_category( array( 'fruits', 'apples', 'bananas', 'cantaloupes', 'guavas', /*etc*/ ) )) {
  2. // These are all fruits
  3. }
  4. ?>

或者在functions.php添加post_is_in_descendant_category()函数代码:

  1. <?php
  2. if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
  3. function post_is_in_descendant_category( $cats, $_post = null ) {
  4. foreach ( (array) $cats as $cat ) {
  5. // get_term_children() accepts integer ID only
  6. $descendants = get_term_children( (int) $cat, 'category' );
  7. if ( $descendants && in_category( $descendants, $_post ) )
  8. return true;
  9. }
  10. return false;
  11. }
  12. }
  13. ?>

然后你可以调用post_is_in_descendant_category()函数来指定某目录下的所有子孙目录的文章页都使用某个模板:

  1. <?php if ( in_category( 'fruit' ) || post_is_in_descendant_category( 'fruit' ) ) {
  2. // These are all fruits…
  3. }
  4. ?>

【源代码】

in_category() 位于 wp-includes/category-template.php.