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

概要

get_the_content フィルタは、現在の投稿情報のコンテンツを取得して加工するために使用されます。このフィルタを使うことで、投稿やページの内容をリアルタイムで編集したり、特定の条件に基づいて内容を変更することができます。以下のような機能を実装する際によく使われます:

  1. 投稿コンテンツにカスタムマークアップを追加する
  2. ソーシャルメディアのシェアボタンを自動的に挿入する
  3. 特定のキーワードをハイライト表示する
  4. コンテンツに広告を追加する
  5. フィルタリングした情報を表示するショートコードを実行する
  6. コンテンツを特定のフォーマットに調整する
  7. 特定の条件に基づいてコンテンツを非表示にする
  8. 他のプラグインやテーマによって追加された内容を統合する

構文

add_filter( 'the_content', 'your_function_name' );

パラメータ

  • $content: 変更される投稿内容の文字列。

戻り値

  • フィルタリング後の投稿内容の文字列。

関連する関数

使用可能なバージョン

  • WordPress 2.0.0 以降

コアファイルのパス

  • /wp-includes/post-template.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('the_content', 'add_thank_you_text');
function add_thank_you_text($content) {
    return $content . '<p>お読みいただきありがとうございます。</p>';
}

引用元: https://example.com/sample1

サンプル2: 投稿内の特定の単語をハイライトする

このコードは、コンテンツ内の「特別」という単語を黄色のハイライトで表示します。

add_filter('the_content', 'highlight_special_word');
function highlight_special_word($content) {
    return str_replace('特別', '<span style="background-color: yellow;">特別</span>', $content);
}

引用元: https://example.com/sample2

サンプル3: ショートコードの実行

このサンプルは、コンテンツ内にショートコードが含まれている場合、そのショートコードを処理します。

add_filter('the_content', 'do_shortcode');

引用元: https://example.com/sample3

サンプル4: コメント数を表示するカスタムメッセージ

このコードは、コメント数を含むカスタムメッセージを投稿のコンテンツの後に追加します。

add_filter('the_content', 'add_comment_count_message');
function add_comment_count_message($content) {
    $comments_count = get_comments_number();
    return $content . '<p>この投稿には ' . $comments_count . ' コメントがあります。</p>';
}

引用元: https://example.com/sample4

サンプル5: 投稿タイプによるフィルタリング

このコードは、特定の投稿タイプの場合にのみメッセージを追加します。

add_filter('the_content', 'add_custom_message_for_post_type');
function add_custom_message_for_post_type($content) {
    if ( 'my_custom_post_type' === get_post_type() ) {
        $content .= '<p>これはカスタム投稿タイプのメッセージです。</p>';
    }
    return $content;
}

引用元: https://example.com/sample5

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


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