LoginSignup
2
2

More than 5 years have passed since last update.

カレントカテゴリIDを取得する関数

Posted at

現在表示しているページのカレントカテゴリIDを取得する関数です。

ソースコード

functions.php
<?php
/**
* @function get_current_cat_id
* @return int
*/
if(!function_exists('get_current_cat_id')){
    function get_current_cat_id(){
        global $wp_query;

        foreach($wp_query->query as $key=>$val){
            if($key == 'category_name'){
                $slug = end(explode('/', $val));
                $cats = get_category_by_slug($slug);
                $output = $cats->term_id;

            }elseif($key == 'cat'){
                $output = $val;
            }
        }

        if(empty($output)){
            return false;
        }

        return $output;
    }
}
?>

パラメータ

なし

使用例

タイトルタグにカテゴリ名を表示したい場合

ソース
<?php
//カテゴリーページの場合【出力:カテゴリ名】
if(is_category()){
    $cur_cat_id = get_current_cat_id();
    if($cur_cat_id){
        $title = get_cat_name($cur_cat_id);
    }
//記事詳細ページの場合【出力:記事名 - カテゴリ名】
}elseif(is_single()){
    $cur_cat_id = get_current_cat_id();
    if($cur_cat_id){
        $title = get_the_title().' - '.get_cat_name($cur_cat_id);
    }
}
?>
<title><?php echo $title; ?><?php bloginfo('name'); ?></title>
2
2
1

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