ワードプレスのwp_insert_term関数の使用方法・解説

概要

wp_insert_term関数は、WordPressのカテゴリや投稿タグを登録する際に使用される便利な関数です。この関数を利用することで、カスタムタクソノミーやその他の用語を追加することもでき、柔軟にタクソノミーデータを管理できます。よく使用される機能には、以下のようなものがあります。

  1. カテゴリの追加
  2. タグの追加
  3. カスタムタクソノミーの用語追加
  4. 用語のスラッグ設定
  5. 用語の説明文の追加
  6. 複数の用語を一度に登録
  7. 既存の用語名の更新
  8. カスタムメタデータの追加

構文

wp_insert_term( $term, $taxonomy, $args );

パラメータ

  • $term (string) : 追加する用語の名前。
  • $taxonomy (string) : 用語が属するタクソノミーの名前(例: ‘category’, ‘post_tag’など)。
  • $args (array) : (オプション)説明やスラッグなど、用語に関する追加情報を格納。

戻り値

成功した場合、用語のIDと、スラッグが含まれる配列を返します。失敗した場合は、WP_Errorオブジェクトを返します。

関連する関数

  • https://refwp.com/?titleonly=1&s=wp_update_term
  • https://refwp.com/?titleonly=1&s=get_term
  • https://refwp.com/?titleonly=1&s=get_terms

使用可能なバージョン

wp_insert_term関数は、WordPress 2.3.0以降で利用可能です。

コアファイルのパス

wp-includes/taxonomy.php

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード1: カテゴリの追加

このコードは、「新しいカテゴリ」という名前のカテゴリを追加します。

$term = '新しいカテゴリ';
$taxonomy = 'category';
$result = wp_insert_term($term, $taxonomy);

引用元: https://developer.wordpress.org/reference/functions/wp_insert_term/

サンプルコード2: タグの追加

このコードは、「新しいタグ」という名前のタグを追加します。

$term = '新しいタグ';
$taxonomy = 'post_tag';
$result = wp_insert_term($term, $taxonomy);

引用元: https://developer.wordpress.org/reference/functions/wp_insert_term/

サンプルコード3: カスタムタクソノミーへの用語追加

このコードは、カスタムタクソノミー「product_category」に対して用語を追加します。

$term = '電子機器';
$taxonomy = 'product_category';
$result = wp_insert_term($term, $taxonomy);

引用元: https://developer.wordpress.org/reference/functions/wp_insert_term/

サンプルコード4: 複数の用語を追加

このコードは、一度に複数の用語を追加します。

$terms = array('特価', 'セール');
$taxonomy = 'product_category';
foreach ($terms as $term) {
    $result = wp_insert_term($term, $taxonomy);
}

引用元: https://developer.wordpress.org/reference/functions/wp_insert_term/

サンプルコード5: 用語の説明を追加

このコードは、新しい用語に説明を追加する方法を示します。

$term = '新しい用語';
$taxonomy = 'post_tag';
$args = array('description' => 'この用語の説明');
$result = wp_insert_term($term, $taxonomy, $args);

引用元: https://developer.wordpress.org/reference/functions/wp_insert_term/

この関数について質問する


上の計算式の答えを入力してください