ワードプレスで記事のカテゴリを取得する関数はget_the_category()です。
記事のカテゴリを取得する関数get_the_category()
// ループ内は、自動的に投稿IDが参照される
$cats = get_the_category();
// ループ外は投稿IDを、引数を与える
$cats = get_the_category( $id );
すこし詳しくみていきます。
ソースコードです。
function get_the_category( $id = false ) {
$categories = get_the_terms( $id, 'category' );
if ( ! $categories || is_wp_error( $categories ) )
$categories = array();
$categories = array_values( $categories );
foreach ( array_keys( $categories ) as $key ) {
_make_cat_compat( $categories[$key] );
}
/**
* Filters the array of categories to return for a post.
*
* @since 3.1.0
* @since 4.4.0 Added `$id` parameter.
*
* @param array $categories An array of categories to return for the post.
* @param int $id ID of the post.
*/
return apply_filters( 'get_the_categories', $categories, $id );
}
ダイレクトに、get_the_terms()関数をコールしていることがわかります。
その後の_make_cat_compat()は、ワードプレスバージョン間の後方互換(Backward Compatibility)を保つための関数です。(公式リファレンス)。get_the_termから得られた値に、「cat_id」などの「カテゴリ」タクソノミー依存の参照名を追加するだけなので、あまり気にしなくて良いでしょう。
投稿のタームを取得する関数get_the_terms()
こちらも該当のソースコードをみてみます。
function get_the_terms( $post, $taxonomy ) {
if ( ! $post = get_post( $post ) )
return false;
$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
$terms = wp_get_object_terms( $post->ID, $taxonomy );
if ( ! is_wp_error( $terms ) ) {
$term_ids = wp_list_pluck( $terms, 'term_id' );
wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );
}
}
/**
* Filters the list of terms attached to the given post.
*
* @since 3.1.0
*
* @param array|WP_Error $terms List of attached terms, or WP_Error on failure.
* @param int $post_id Post ID.
* @param string $taxonomy Name of the taxonomy.
*/
$terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );
if ( empty( $terms ) )
return false;
return $terms;
}
get_object_term_cache(), wp_cache_add()という一時キャッシュ(変数を、1リクエストの間だけ保持します)を利用していることがわかります。
つまり、同一のリクエストにおいては、何度get_the_term()を読んでも、クエリは発生せず、キャッシュを使いまわしてくれることがわかります。
投稿のカテゴリの取得に関するまとめ
get_the_category()は、get_the_termsとほぼ同値です。get_the_category()フィルターを意識するかどうかもありますが、個人的には、できるだけ一貫性の高いコーディングをするため、タクソノミーかによらず、いつも、get_the_terms()だけを使いたい気持ちになります。
また、get_the_xxxx() などの、ワードプレスループに依存した関数は、こう言った、filterや、キャッシュ機構などを含んでいる高級な処理を行っていることがわかりました。そのようなケースがあるかわかりませんが、できるだけローレベルなSQLクエリ結果に直接アクセスするには、wp_get_object_terms()関数を呼ぶことになりそうです。
「投稿のカテゴリを取得する関数」には、関数の抽象度によって、いくつかの選択肢があることがわかりました。どのレベルの関数を利用するかは、意識して使い分けることもあるかもしれませんね。