ワードプレスのterm_descriptionフィルタの使用方法・解説

概要

term_descriptionフィルタは、WordPressのタームの説明文を取得するために使用されるフィルタです。このフィルタを使うことで、タームの説明文を変更したり、カスタマイズしたりすることができます。以下は、term_descriptionフィルタがよく使われる機能の例です。

  1. タームの説明文を動的に変える
  2. タームに基づいた特定の条件で説明文を追加
  3. タームの説明文にHTMLを追加して整形
  4. 外部データベースからタームの説明文を取得
  5. ユーザーのロールに応じてタームの説明文を変更
  6. コードの短縮を使用してタームの情報を取得
  7. カスタムプラグイン内でタームの説明文をフィルタリング
  8. SEOのためにタームの説明を最適化

構文

apply_filters('term_description', $description, $term_id, $term);

パラメータ

  • $description (string): タームの既存の説明文
  • $term_id (int): タームのID
  • $term (object): タームオブジェクト

戻り値

フィルタを通過した最終的なタームの説明文 (string)

関連する関数

term_description

使用可能なワードプレスバージョン

  • すべてのバージョンで使用可能

コアファイルのパス

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: デフォルトのターム説明文を変更する

このサンプルコードは、特定のタームの説明文を変更する方法を示しています。

add_filter('term_description', 'custom_term_description', 10, 3);

function custom_term_description($description, $term_id, $term) {
    if ($term_id == 10) { // タームIDが10のとき
        return 'カスタムの説明文';
    }
    return $description; // デフォルトの説明文を返す
}

引用元: https://developer.wordpress.org/reference/hooks/term_description/

サンプルコード2: HTMLを追加する

このコードは、タームの説明文にHTMLタグを追加する方法を示します。

add_filter('term_description', 'add_html_to_term_description');

function add_html_to_term_description($description) {
    return '<strong>' . $description . '</strong>'; // 説明文を太字にする
}

引用元: https://developer.wordpress.org/reference/hooks/term_description/

サンプルコード3: 外部データベースからの取得

このサンプルは、外部のデータベースからタームの説明文を取得する例です。

add_filter('term_description', 'get_description_from_external_db');

function get_description_from_external_db($description, $term_id) {
    // 外部データベースからの情報を取得
    $external_description = /* 外部DBから取得する処理 */;
    return $external_description ? $external_description : $description;
}

引用元: https://developer.wordpress.org/reference/hooks/term_description/

サンプルコード4: ユーザーのロールに基づく説明文

このコードでは、ユーザーのロールに応じてタームの説明文を変えています。

add_filter('term_description', 'role_based_term_description');

function role_based_term_description($description) {
    if (current_user_can('administrator')) {
        return '管理者のための特別な説明文';
    }
    return $description;
}

引用元: https://developer.wordpress.org/reference/hooks/term_description/

サンプルコード5: ショートコードの使用

このコードは、ショートコードを利用して説明文を表示します。

add_filter('term_description', 'shortcode_in_term_description');

function shortcode_in_term_description($description) {
    return do_shortcode($description); // 説明文内のショートコードを実行
}

引用元: https://developer.wordpress.org/reference/hooks/term_description/

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


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