説明
wp_insert_term() は、新しいタームを作成する関数です。
基本構文
wp_insert_term( string $term, string $taxonomy, array|string $args = array() ): array|WP_Error
引数
$term:ターム名$taxonomy:タクソノミー名$args:slug、parent、descriptionなど
戻り値
term_id と term_taxonomy_id を含む配列。失敗時は WP_Error。
使い方(サンプル)
$r = wp_insert_term( '音楽', 'category', array( 'slug' => 'music' ) );
if ( is_wp_error( $r ) ) {
error_log( $r->get_error_message() );
}
注意点
- 同名のタームが既にあると
WP_Errorが返ります。事前にterm_exists()で確認します。
実務での使いどころ
- ターム(カテゴリーなど)を、プログラムから作るとき。
- インポートの処理で、必要なタームを作るとき。
よくあるミスと対処
- 戻り値が
WP_Errorのときを、考えていない。すでに同じタームがあると、term_existsのエラーが返る。 - 戻り値を、そのままIDとして使っている。戻り値は、
term_idとterm_taxonomy_idを持つ配列。 - 作る前に、
term_exists()で確認していない。
NG例
$id = wp_insert_term( 'important', 'news_cat' ); // 配列かエラーが返る
OK例
$result = wp_insert_term( 'important', 'news_cat' );
if ( is_wp_error( $result ) ) {
return;
}
$term_id = (int) $result['term_id'];
使い分け早見表
| やりたいこと | 使うもの |
|---|---|
| タームを作る | wp_insert_term() |
| タームを更新する | wp_update_term() |
| タームを削除する | wp_delete_term() |
関連項目
term_exists()、wp_update_term()、wp_delete_term()
公式リファレンス:wp_insert_term() | Function | WordPress Developer Resources

コメント