LoginSignup
2
2

More than 5 years have passed since last update.

【WP-Champloo】指定したカテゴリに所属するのかを調べる関数

Posted at

現在の投稿が指定したカテゴリに所属するのかを調べる関数です。
複数の場合は配列形式で指定します。

ソースコード

functions.php
<?php
/**
* @function in_parent_category
* @param cats_id(array)
* @return bool
*/
if(!function_exists('in_parent_category')){
    function in_parent_category($cats_id = null){
        global $post;

        foreach((array)$cats_id as $cat_id){
            $parent_cats = get_term_children(intval($cat_id), 'category');
            if($parent_cats && in_category($parent_cats, $post->ID)){
                return true;
            }
        }

        return false;
    }
}
?>

パラメータ

cats_id(カテゴリID)

使用例

ソース
<?php if(in_parent_category(3)): ?>
<p>カテゴリID「3」に所属しています。</p>
<?php endif; ?>

複数ある場合

ソース
<?php if(in_parent_category(array(10,20))): ?>
<p>カテゴリID「10」または「20」に所属しています。</p>
<?php endif; ?>
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2