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

概要

wp_set_object_terms関数は、投稿情報などにタクソノミーを設定するために使用されます。この関数を使用すると、特定のオブジェクトに対してターム(カテゴリーやタグ)を追加したり、既存のタームを更新したりすることができます。主な用途としては以下のようなケースがあります。

  1. 投稿にカテゴリーを追加する
  2. 投稿にタグを追加する
  3. カスタム投稿タイプにタクソノミーを設定する
  4. 特定のユーザーに役割を割り当てる
  5. タクソノミーの基づいたフィルタリング機能を実装する
  6. タームに基づくクエリを生成する
  7. リレーショナルデータモデルを構築する
  8. メタボックスを利用してバックエンドからタクソノミーを設定する

構文

wp_set_object_terms( int $object_id, mixed $terms, string $taxonomy, bool $append = false )

パラメータ

  • $object_id (int): タクソノミーを設定する対象のオブジェクトのID。
  • $terms (mixed): 設定するタームのID、スラッグ、または名前の配列。
  • $taxonomy (string): 設定するタクソノミーの名前。
  • $append (bool): 既存のタームに追加するかどうか(デフォルトはfalse)。

戻り値

成功した場合、設定されたタームの配列を返します。失敗した場合はfalseを返します。

関連する関数

使用可能なバージョン

この関数はWordPress 2.5.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: 投稿にタグを追加する

このコードは、特定の投稿にタグを追加する方法を示しています。

$post_id = 123; // 投稿のID
$tags = array('tag1', 'tag2');
wp_set_object_terms($post_id, $tags, 'post_tag');

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

サンプルコード2: カスタムタクソノミーを設定する

このコードは、カスタム投稿タイプのオブジェクトにタクソノミーを設定する例です。

$custom_post_id = 456; // カスタム投稿のID
$taxonomy_terms = array('custom-term1', 'custom-term2');
wp_set_object_terms($custom_post_id, $taxonomy_terms, 'custom_taxonomy');

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

サンプルコード3: 既存のタームを更新する

このコードは、既存のタームを更新する方法を示しています。

$post_id = 789; // 投稿のID
$new_terms = array('updated-tag1', 'updated-tag2');
wp_set_object_terms($post_id, $new_terms, 'post_tag', true);

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

サンプルコード4: タームを削除する

このコードは、既存のタームを削除することができる方法を示しています。

$post_id = 123; // 投稿のID
$to_remove_terms = 'tag-to-remove';
wp_set_object_terms($post_id, array($to_remove_terms), 'post_tag', false);

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

サンプルコード5: カスタム投稿タイプでタームを設定

このコードは、カスタム投稿タイプの投稿にタームを設定する例です。

$custom_post_id = 321; // カスタム投稿のID
$terms_array = array('term1', 'term2');
wp_set_object_terms($custom_post_id, $terms_array, 'custom_taxonomy');

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

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


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