毎回毎回、どうやったけと迷ってしまう、「現在のカテゴリ、タグを取得する方法」について、
blog.ks-product.com/ さんが関数を作ってくださっていたので引用させていただきます。
もう迷わない!アーカイブページで現在のカテゴリ・タグの情報を簡単に取得する方法【WordPress】
1. 以下の関数をそのまま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 |
/* アーカイブページで現在のカテゴリー・タグ・タームを取得する */ function get_current_term(){ $id; $tax_slug; if(is_category()){ $tax_slug = "category"; $id = get_query_var('cat'); }else if(is_tag()){ $tax_slug = "post_tag"; $id = get_query_var('tag_id'); }else if(is_tax()){ $tax_slug = get_query_var('taxonomy'); $term_slug = get_query_var('term'); $term = get_term_by("slug",$term_slug,$tax_slug); $id = $term->term_id; } return get_term($id,$tax_slug); } |
2. あとはアーカイブ(category.php、tag.phpなど)テンプレートの任意の場所に以下のソースコードを記述するだけ!
|
1 2 3 4 5 6 7 8 |
//カテゴリ・タグ・カスタムタクソノミー オブジェクトを取得 $term = get_current_term(); //以下は必要に応じて記述 echo $term->name; //名前を表示 echo $term->slug; //スラッグを表示 echo $term->description; //説明文を表示 echo $term->count; //投稿数を表示 |
今まではアーカイブの種類ごとに記述を変更する必要がありましたが、この関数で各アーカイブ共通の記述で情報が取得できるようになるので重宝するかと思います。
※この関数は投稿ページ(single.php)では使用できません。投稿ページではget_the_category()やget_term()をお使いください。
blog.ks-product.com/ さんありがとうございます。