2024.08.11(更新日: 2024.08.11)
タグ一覧ページでget_queried_object()を使ってみた

はじめに
TCDの記事によると、get_queried_object()で、各ページのクエリ情報を取得することができる。
取得したものを変数に格納する
まずはこちらの一文で、$termという変数に、get_queried_object(); で取得したものを入れておこう。

変数に格納されたオブジェクトを出力してみた
こちらの記事によると、PHPで変数の内容を出力するには、var_dumpを使うので、これで$termの中身を確認してみた。
プログラミングのタグ一覧ページの場合、以下が出力された。
object(WP_Term)#8210 (11) { ["term_id"]=> int(148) ["name"]=> string(21) "プログラミング" ["slug"]=> string(10) "programing" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(148) ["taxonomy"]=> string(8) "post_tag" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(2) ["filter"]=> string(3) "raw" ["term_order"]=> string(1) "4" }
青春18きっぷのタグ一覧ページの場合は、以下。
object(WP_Term)#8210 (11) { ["term_id"]=> int(188) ["name"]=> string(17) "青春18きっぷ" ["slug"]=> string(18) "b-seishun-18-kippu" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(188) ["taxonomy"]=> string(8) "post_tag" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(5) ["filter"]=> string(3) "raw" ["term_order"]=> string(1) "0" }
オブジェクトのプロパティの意味を調べてみた
WP_Termというオブジェクトの中に、プロパティが11個ある。
プログラミングのタグ一覧ページで取得できたWP_Termオブジェクトのプロパティと意味をまとめてみた。
プロパティ | 意味 |
term_id | タームのID |
name | タームの名前 |
slug | タームのスラッグ |
term_group | 親タームのID |
term_taxonomy_id | タームが属するタクソノミーのID(出力結果を見ると、term_idと同じだった) |
taxonomy | タームが属するタクソノミーの名前 |
description | タームの説明 |
parent | 親タームのID(term_groupと同じ?分けて使う場面がありそう) |
count | このタームが使われている回数 |
filter | タームオブジェクトのサニタイズレベル(参考 : WordPressのタクソノミーとタームをマスターする | 滋賀/京都/大阪でホームページ制作ならYUKiYURi WEB) |
term_order | タームの並び順(プラグイン「Custom Taxonomy Order」で追加) |
タームとは
タグの場合、プログラミングや青春18きっぷのこと。
タクソノミーとは
カテゴリーやタグのこと。
オブジェクトからプロパティを出力する方法
プロパティは以下のような形で出力できる。

nameの使用箇所
タグ一覧ページのタイトルで使用している。

一度、以下のように変数に入れて、

タイトルのところで使用している。

スコープを狭くしたほうがいいかもしれない。
リファクタリング可能だ。
countの使用箇所
タイトルの後で、そのタグの記事数を表示させている。


term_orderの使用箇所
管理画面で設定した順番で、サイドバーのタグが表示されている。


青春18きっぷのterm_orderは0で、プログラミングのterm_orderは4である。


投稿ID : 23748
コメントを残す