概要
get_the_excerpt
フィルタは、投稿情報の抜粋記事を取得する際に使用され、特に投稿の内容を短縮し、簡略化するために便利です。このフィルタによって、抜粋の内容を自由にカスタマイズできるため、独自のデザインや機能を実装する際に役立ちます。具体的には、以下のような場面で一般的に使われます。
- 投稿リストやアーカイブページの表示調整
- 抜粋内容の追加情報や特別なマークアップを挿入
- 外部データベースやAPIから取得した内容との統合
- 抜粋に特定のキーワードを強調表示
- コンテンツを条件に応じてフィルタリング
- 新しいフォーマットやスタイルにアレンジ
- 多言語対応のためのテキスト調整
- SEO最適化のためのメタ情報統合
このフィルタは、主に投稿の抜粋をカスタマイズするために使用されます。
構文
add_filter('get_the_excerpt', 'custom_excerpt_function');
パラメータ
$excerpt
(string) – 現在の抜粋の内容。$post
(WP_Post) – 抜粋が取得される投稿のオブジェクト。
戻り値
- (string)カスタマイズされた抜粋の内容。
関連する関数
https://refwp.com/?titleonly=1&s=get_the_excerpt
使用可能なバージョン
- WordPress 1.5以降
コアファイルのパス
wp-includes/post-template.php
サンプルコード
サンプルコード1: 抜粋に特定の文字列を追加
function add_custom_text_to_excerpt($excerpt) {
return $excerpt . '...もっと読む';
}
add_filter('get_the_excerpt', 'add_custom_text_to_excerpt');
このコードは、すべての投稿の抜粋の最後に「…もっと読む」を追加します。
サンプルコード2: 抜粋の長さを変更
function custom_excerpt_length($length) {
return 20; // 抜粋を20単語に設定
}
add_filter('excerpt_length', 'custom_excerpt_length');
このコードは抜粋の長さを20単語に設定します。
サンプルコード3: HTMLを許可
function allow_html_in_excerpt($excerpt) {
return wp_kses_post($excerpt); // HTMLタグを許可
}
add_filter('get_the_excerpt', 'allow_html_in_excerpt');
このコードは抜粋内でHTMLタグを使用可能にします。
サンプルコード4: 抜粋の前に日付を追加
function prepend_date_to_excerpt($excerpt) {
$post_date = get_the_date();
return $post_date . ': ' . $excerpt;
}
add_filter('get_the_excerpt', 'prepend_date_to_excerpt');
このコードは、すべての抜粋の前に投稿の日付を追加します。
サンプルコード5: 特定の投稿に異なる抜粋を表示
function conditional_excerpt($excerpt) {
if (is_single('特定の投稿スラッグ')) {
return 'この特定の投稿のための特別な抜粋。';
}
return $excerpt;
}
add_filter('get_the_excerpt', 'conditional_excerpt');
このコードは、特定の投稿に対して異なる抜粋を表示させる機能を持っています。
この関数のアクションでの使用可能性
アクション | 使用可否 |
---|---|
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 |
このフィルタは、特定のバージョンで非推奨や削除されていません。