カスタム投稿タイプの「meta property=”og:description”」などのmetaプロパティをシングルページで出力させる方法。
まずは、デフォルトの投稿タイプ(post)を「&&is_singular(‘post’)」で設定する必要がある
if (is_single()&&is_singular('post')){
if(have_posts()): while(have_posts()): the_post();
echo '<meta property="og:title" content="'; the_title(); echo '">';echo "\n";
echo '<meta property="og:description" content="'.mb_substr(get_the_excerpt(), 0, 120).'">';echo "\n";
echo '<meta property="og:url" content="'; the_permalink(); echo '">';echo "\n";
echo '<meta property="og:type" content="article">';echo "\n";
endwhile; endif;
}
続けて、カスタム投稿タイプ
※descriptionを投稿内の文章から取得する場合はデフォルトと同じです。
例:カスタム投稿タイプが「catering_plan」で、descriptionをカスタムフィールド「delivery_note」から取得し、100文字以内で区切りのいいところでカットするという方法。(区切りとは「、」や「。」の句読点)
if (is_single() && is_singular('catering_plan')) {
if (have_posts()): while (have_posts()): the_post();
// 元のテキスト取得
$text_items = get_field('delivery_note');
// 改行削除 → タグ削除 → 連続スペース削除
$text_items = wp_strip_all_tags($text_items);
$text_items = preg_replace('/\s+/', ' ', $text_items);
$text_items = trim($text_items);
// 100文字で一旦切る
$short = mb_substr($text_items, 0, 100);
// 最後の句読点以降を削除して自然な文章にする
$description = preg_replace('/[^、。..!?!?]*$/u', '', $short);
// もし句読点が見つからず空になった場合は100文字そのまま
if ($description === '') {
$description = $short;
}
echo '<meta property="og:title" content="'; the_title(); echo '">' . "\n";
echo '<meta property="og:description" content="' . esc_attr($description) . '">' . "\n";
echo '<meta property="og:url" content="'; the_permalink(); echo '">' . "\n";
echo '<meta property="og:type" content="article">' . "\n";
endwhile; endif;
}