プラグインなしでSEO実装をする案件にて。
カスタム投稿+カスタムフィールドの構築で、SEO対策として記事本文の最初の130文字をdiscriptionに入れてほしいという要望がありました。
本来なら、th_content
から130文字抜くだけなので簡単ですが、カスタムフィールドだとそれができませんね。
なので、カスタムフィールドの値を全部取ってきて、th_content
の中に自動で入れ込み、そこから130文字抜き出そうという実装です。
ポイントなのが、柔軟コンテンツをループして1つのテキストにまとめる です。
// the_contentで取得する本文に、カスタムフィールドの値を含める
function set_contents($post_id) {
if(!wp_is_post_revision($post_id) && get_post_type($post_id) === 'contents') {
remove_action('wp_insert_post', 'set_contents');
$contents_description = '';
$contents_inner = get_field('contents_inner', $post_id);
$contents_article_migration = get_field('contents_article-migration', $post_id);
// 柔軟コンテンツをループして1つのテキストにまとめる
if($contents_inner) {
foreach($contents_inner as $item) {
$post_set_type = $item['acf_fc_layout'];
if($post_set_type === 'contents_inner_h2') {
$field_val = $item['contents_inner_h2_title'];
if($field_val) {
$contents_description .= $field_val;
}
} elseif($post_set_type === 'contents_inner_h3') {
$field_val = $item['contents_inner_h3_title'];
if($field_val) {
$contents_description .= $field_val;
}
} elseif($post_set_type === 'contents_inner_h4') {
$field_val = $item['contents_inner_h4_title'];
if($field_val) {
$contents_description .= $field_val;
}
} elseif($post_set_type === 'contents_inner_h5') {
$field_val = $item['contents_inner_h5_title'];
if($field_val) {
$contents_description .= $field_val;
}
} elseif($post_set_type === 'contents_inner_h6') {
$field_val = $item['contents_inner_h6_title'];
if($field_val) {
$contents_description .= $field_val;
}
} elseif($post_set_type === 'contents_inner_text') {
$field_val = $item['contents_inner_text_text'];
if($field_val) {
$contents_description .= $field_val;
}
} else {}
}
}
$update_post = array(
'ID' => $post_id,
'post_type' => 'contents',
'post_content' => $contents_article_migration . $contents_description,
);
wp_update_post($update_post);
add_action('wp_insert_post', 'set_contents');
}
}
add_action('wp_insert_post', 'set_contents', 10, 1);
こうすることで、更新ボタンを押したときに、the_content
の中に自動でカスタムフィールドの値が全部入るようになります。