CHIPS

制作チップス

特定の親カテゴリとその子カテゴリに関する条件分岐

2025年6月10日

カテゴリー: 制作チップス

親カテゴリで条件分岐

カテゴリーアーカイブページの場合

カテゴリID:10とそれに属する子カテゴリの投稿を出力する

<?php 
$specific = '10';
$cat = get_the_category(); $parent_id = $cat[0]->category_parent;?>
<?php if (is_category($specific)||$parent_id == $specific):?>
  ここに処理を記述
<?php endif;?>

single.phpで出力したい場合

functions.phpに下記を記述

function post_is_in_descendant_category( $cats, $_post = null ){
   foreach ( (array) $cats as $cat ) {
         $descendants = get_term_children( (int) $cat, 'category');
          if ( $descendants && in_category( $descendants, $_post ) )
              return true;
   }
   return false;
}

single.phpの出力したい箇所へ下記のコードを記述する。

<?php if ( in_category(親カテゴリID) || post_is_in_descendant_category(親カテゴリID) ): ?>
// 「親カテゴリ」もしくは「親カテゴリ」に属する子カテゴリーのものであった場合の出力内容
<?php else: ?>
//  それ以外の出力内容
<?php endif; ?>

親カテゴリ:music
子カテゴリ:hip-hop、rock

<?php if ( in_category('music') ||
post_is_in_descendant_category( get_term_by( 'slug', 'hip-hop', 'rock' ) )): ?>
// 「親カテゴリ」もしくは「親カテゴリ」に属する子カテゴリーのものであった場合の出力内容
<?php else: ?>
//それ以外の出力内容
<?php endif; ?>