3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Wordpress】投稿ページ(single.php)において、複数ページ(複数テンプレート)に出し分ける方法

Last updated at Posted at 2019-12-05

実現したかったこと

ひとつの投稿において、情報によってページを切り替えられるようにしたい

投稿が一つのお店のページになっていて、さらにタブでメニューやクーポンをぶら下げるような作りに。
要は食べログやぐるなびのイメージです。
各ページの出しわけは、URLにパラメーターを追加することで判定します。

投稿(美味しい餃子 渋谷店)のトップURL
https://hogehoge.com/cat/美味しい餃子渋谷店/

投稿(美味しい餃子 渋谷店)のメニューURL
https://hogehoge.com/cat/美味しい餃子渋谷店/?info=menu

投稿(美味しい餃子 渋谷店)のアクセスURL
https://hogehoge.com/cat/美味しい餃子渋谷店/?info=access

やること

1. テンプレの用意

トップ用のテンプレとは別に、menu用、access用のテンプレを用意します。
single.php
single-menu.php
single-access.php

2. function.phpにフィルターフックを追加

single_templateに対してフィルターフックを追加します。
以下、ソースの例です。

function.php
function shop_template_switch($template) {
	$new_template = $template;
    if (isset($_GET['info'])) {
        $new_template = 'single-' . esc_html($_GET['info']) . '.php';
        if (is_array($template)) {
            $new_template = array(
                $new_template,
                isset($template[1]) ? $template[1] : 'single.php'
                );
        } else {
            $new_template = preg_replace('/[^\/]+\.php$/i', $new_template, $template);
            if (!file_exists($new_template)) {
                $new_template = $template;
            }
        }
    }
    return $new_template;
}
add_filter('single_template', 'shop_template_switch');

3. 完成

URLに各パラメーターを追加し、表示されれば完成です。
https://hogehoge.com/cat/美味しい餃子渋谷店/
https://hogehoge.com/cat/美味しい餃子渋谷店/?info=menu
https://hogehoge.com/cat/美味しい餃子渋谷店/?info=access

パラメーター名でテンプレを作れば、さらにページを増やしていけます。

例:メッセージページを以下のURLで作成する場合
https://hogehoge.com/cat/美味しい餃子渋谷店/?info=message
→ single-message.php

特定のカスタム投稿タイプの場合

複数のカスタム投稿タイプがある場合など、特定のカスタム投稿タイプだけに反映させたいこともあると思います。
function.phpの記述を以下のようにすれば、特定のカスタム投稿タイプだけで実装することができます。

例:カスタム投稿タイプ「shop」にだけ適用したい場合

function.php
function shop_template_switch($template) {
	$new_template = $template;
	$post = get_queried_object();
	if (is_singular( 'shop', $post)) {
		if (isset($_GET['info'])) {
			$new_template = 'single-' . esc_html($_GET['info']) . '.php';
			if (is_array($template)) {
				$new_template = array(
					$new_template,
					isset($template[1]) ? $template[1] : 'single-shop.php'
					);
			} else {
				$new_template = preg_replace('/[^\/]+\.php$/i', $new_template, $template);
				if (!file_exists($new_template)) {
					$new_template = $template;
				}
			}
		}
	}
    return $new_template;
}
add_filter('single_template', 'shop_template_switch');

参考サイト

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?