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

概要

get_the_title_rssフィルタは、フィード向けの投稿タイトルを取得する際にできるカスタマイズを行うために使用されます。このフィルタを利用すると、RSSフィードに表示されるタイトルを変更したり、特定の条件に基づいて処理を行ったりすることが可能です。以下は、このフィルタがよく使われる代表的な機能です。

  1. タイトルのフォーマット変更
  2. タイトルに特定の文字列を追加
  3. タイトルのトリミング
  4. 特定の条件下でタイトルを非表示
  5. タイトルの翻訳やローカライズ
  6. 投稿タイプごとのタイトルカスタマイズ
  7. 特定のユーザーに対して異なるタイトルを表示
  8. タイトルのエンコーディング変更

get_the_title_rssフィルタの構文は以下の通りです。

apply_filters('get_the_title_rss', $title, $post_id);

パラメータ

  • $title: 元の投稿タイトル。
  • $post_id: 対象の投稿のID。

戻り値

変更後の投稿タイトルを返します。

関連する関数

関連する関数のリストはこちら

使用可能なバージョン

WordPress 2.0.0以降で使用可能です。

コアファイルのパス

このフィルタは、wp-includes/feed.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('get_the_title_rss', 'custom_title_for_rss', 10, 2);

function custom_title_for_rss($title, $post_id) {
    return $title . ' (フィード用)';
}

このサンプルコードは、RSSフィードで表示されるタイトルに “(フィード用)” という文字列を追加します。

サンプル2: タイトルを短縮

add_filter('get_the_title_rss', 'shorten_title_for_rss', 10, 2);

function shorten_title_for_rss($title, $post_id) {
    return mb_substr($title, 0, 30) . '...';
}

このサンプルでは、長いタイトルの最初の30文字だけを表示し、表示を短縮します。

サンプル3: 特定の投稿IDに対してタイトルを変更

add_filter('get_the_title_rss', 'modify_title_for_specific_post', 10, 2);

function modify_title_for_specific_post($title, $post_id) {
    if ($post_id == 123) {
        return '特別なタイトル';
    }
    return $title;
}

このサンプルコードでは、投稿IDが123の場合、タイトルを “特別なタイトル” に変更します。

サンプル4: タイトルのHTMLエンコードを無効にする

add_filter('get_the_title_rss', 'disable_html_entity_encode', 10, 2);

function disable_html_entity_encode($title, $post_id) {
    return html_entity_decode($title);
}

このサンプルは、RSSフィードでのタイトルに対してHTMLエンコードを解除します。

サンプル5: 投稿タイプに応じたタイトルカスタマイズ

add_filter('get_the_title_rss', 'custom_title_based_on_post_type', 10, 2);

function custom_title_based_on_post_type($title, $post_id) {
    $post_type = get_post_type($post_id);
    if ($post_type == 'special_post_type') {
        return '特別な投稿タイプのタイトル';
    }
    return $title;
}

このサンプルコードでは、特定の投稿タイプに基づいてタイトルを変更します。

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


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