Web production note

 【更新日 :

【WordPress】カスタム投稿タイプ記事のタームの情報を取得する

Category:
WordPress

カスタム投稿タイプ記事のタームの情報を取得するサンプルコードです。

$terms = get_the_terms( $post -> ID, 'タクソノミー名' );
foreach( $terms as $term ) {
	$term_slug = esc_html( $term -> slug );
	$term_id = esc_html( $term -> term_taxonomy_id );
	$term_name = esc_html( $term -> name );
}

一件だけ取得する

登録されているタームが一件のみであれば、ループを回さずに取得できます。

$terms = get_the_terms( $post -> ID, 'タクソノミー名' );
$term_name = esc_html( $terms[0] -> name );
$term_id = esc_html( $term[0] -> term_taxonomy_id );
$term_slug = esc_html( $terms[0] -> slug );

get the termsの戻り値

get the termsでは以下の内容が取得できます。

stdClass Object
(
    [term_id] =>
    [name] =>
    [slug] =>
    [term_group] => 
    [term_order] => 
    [term_taxonomy_id] =>
    [taxonomy] =>
    [description] => 
    [parent] =>
    [count] =>
    [object_id] =>
)

関連リンク

参考リンク