term_exists() の使い方|説明・引数・注意点

説明

term_exists() は、指定したタームが存在するかを調べる関数です。

基本構文

term_exists( int|string $term, string $taxonomy = '', int $parent_term = null ): mixed

引数

  • $term:ID、スラッグ、または名前
  • $taxonomy:タクソノミー名
  • $parent_term:親タームのID

戻り値

存在しなければ 0 または null。存在すればタームIDを含む配列。

使い方(サンプル)

if ( ! term_exists( 'news', 'category' ) ) {
	wp_insert_term( 'news', 'category' );
}

注意点

  • 戻り値が配列の場合と整数の場合があるため、真偽値として使うのが安全です。

実務での使いどころ

  • ターム(カテゴリーなど)を作る前に、すでにあるかを確認するとき。
  • ターム名やスラッグから、ターム(のID)を調べるとき。

よくあるミスと対処

  • 戻り値の型が、条件によって違う。タクソノミーを指定すると配列(term_id・term_taxonomy_id)、省略するとIDが返る。存在しないときは 0 や null。
  • 戻り値を、そのままIDとして使っている。配列のときは、$result['term_id'] を使う。
  • $taxonomy を省略し、意図しないタクソノミーのタームに当たる。

NG例

$id = term_exists( 'important', 'news_cat' );
wp_set_post_terms( $post_id, array( $id ), 'news_cat' ); // 配列を渡している

OK例

$term = term_exists( 'important', 'news_cat' );
if ( $term ) {
	$term_id = (int) $term['term_id'];
}

使い分け早見表

やりたいこと 使うもの
タームがあるか確認 term_exists()
タームを作る wp_insert_term()
タームを取得 get_term_by()

関連項目

wp_insert_term()、get_term_by()

公式リファレンス:term_exists() | Function | WordPress Developer Resources

コメント

タイトルとURLをコピーしました