はじめに
WordPressのカスタム投稿タイプ news
において、通常の本文(post_content
)ではなく、カスタムフィールドに用意した本文をメタディスクリプションやコンテンツ出力時に利用 したい場合があります。
本記事では、その方法を解説します。
実装方法
1. the_content フィルターを使い、本文をカスタムフィールドの値に置き換える
まず、the_content
フィルターを利用し、テンプレート内で the_content()
を使用している箇所の本文をカスタムフィールドの値に変更します。
functions.php に追加
function custom_news_content_filter($content) {
global $post;
// カスタム投稿タイプ 'news' の場合のみ適用
if (is_singular('news')) {
// カスタムフィールドの値を取得(カスタムフィールド名が 'custom_news_content' の場合)
$custom_content = get_post_meta($post->ID, 'custom_news_content', true);
// カスタムフィールドが設定されていれば、デフォルトの本文を置き換え
if (!empty($custom_content)) {
return wpautop($custom_content); // 自動で段落を付与
}
}
return $content;
}
// the_content フィルターを適用
add_filter('the_content', 'custom_news_content_filter');
解説
the_content
フィルターを使用し、WordPressのすべてのthe_content()
出力箇所 に影響を与える。get_post_meta($post->ID, 'custom_news_content', true)
でカスタムフィールドから本文を取得。- カスタムフィールドが設定されている場合のみ置き換える。
wpautop()
を適用し、段落 (<p>
) を適切に挿入。
2. SEO用の <meta name="description"> を変更する
本文の変更だけでなく、メタディスクリプションもカスタムフィールドの値を使いたい場合は、以下のコードを追加します。
Yoast SEO の場合
function custom_news_yoast_meta_desc($desc) {
if (is_singular('news')) {
global $post;
$custom_desc = get_post_meta($post->ID, 'custom_news_description', true);
// カスタムディスクリプションが設定されていれば適用
if (!empty($custom_desc)) {
return $custom_desc;
}
}
return $desc;
}
add_filter('wpseo_metadesc', 'custom_news_yoast_meta_desc');
All in One SEO の場合
function custom_news_aioseo_meta_desc($desc) {
if (is_singular('news')) {
global $post;
$custom_desc = get_post_meta($post->ID, 'custom_news_description', true);
// カスタムディスクリプションが設定されていれば適用
if (!empty($custom_desc)) {
return $custom_desc;
}
}
return $desc;
}
add_filter('aioseo_description', 'custom_news_aioseo_meta_desc');
解説
wpseo_metadesc
(Yoast SEO)やaioseo_description
(All in One SEO)のフィルターを使い、SEOプラグインが出力するメタディスクリプションをカスタムフィールドの値に置き換える。custom_news_description
というカスタムフィールドに保存されたテキストを使用。
3. Excerpt(抜粋)を変更する
抜粋(the_excerpt()
)をカスタムフィールドの値に変更したい場合は、以下のコードを追加します。
function custom_news_excerpt_filter($excerpt) {
global $post;
// カスタム投稿タイプ 'news' の場合のみ適用
if ($post->post_type === 'news') {
$custom_excerpt = get_post_meta($post->ID, 'custom_news_excerpt', true);
// カスタムフィールドが設定されていれば置き換え
if (!empty($custom_excerpt)) {
return $custom_excerpt;
}
}
return $excerpt;
}
// the_excerpt フィルターを適用
add_filter('the_excerpt', 'custom_news_excerpt_filter');
解説
the_excerpt
フィルターを使用し、WordPressの抜粋をカスタムフィールドの値に変更。custom_news_excerpt
というカスタムフィールドの値を抜粋として表示。
まとめ
✅ the_content
フィルターで、テーマテンプレート内の本文をカスタムフィールドに置き換え
✅ SEO用の <meta name="description">
もカスタムフィールドの値に適用
✅ the_excerpt
もカスタムフィールドの値に変更可能
この方法を適用すれば、news
のカスタム投稿タイプの本文を一括でカスタマイズし、一貫した表示が可能になります
コメント