CPTUI で作った、投稿タイプ の シングルページを2種類表示したい。
2024年10月19日CPTUI で作った、投稿タイプ の シングルページを2種類表示したい。
CPTUIで、投稿タイプAを作り、そこに記事を作ると、2つのシングルページができる。
● https://***.com/投稿タイプA/記事123 ←こっちがホンモノ
● https://***.com/投稿タイプB/記事123 ←こっちはコピーされてる
———————————————
①CPTUI にて、投稿タイプA、投稿タイプBをつくる。
②function.php に、以下のコードを最後の方に追加する。
//CPTUI で作った、投稿タイプ の シングルページを2種類表示したい。
function custom_rewrite_rules() {
add_rewrite_rule(
‘^投稿タイプB/([^/]+)/?’,
‘index.php?post_type=投稿タイプA&name=$matches[1]’,
‘top’
);
}
add_action(‘init’, ‘custom_rewrite_rules’);
function load_custom_template($template) {
if (is_singular(‘投稿タイプA‘) && strpos($_SERVER[‘REQUEST_URI’], ‘/投稿タイプB/’) !== false) {
// `投稿タイプB` URL用のカスタムテンプレートを読み込み
$new_template = locate_template(array(‘single-投稿タイプB.php’));
if ($new_template) {
return $new_template;
}
}
return $template;
}
add_filter(‘template_include’, ‘load_custom_template’);
③投稿タイプAの方に、記事を追加していく。
④どちらともにも、その記事のシングルページが作られる。
※投稿タイプBに、記事を作るのはNG
※functionをいじるのは危険なので、準備・コピーしてから。
※作ったら、パーマリンクの設定を更新してあげること。