LoginSignup
10
16

More than 3 years have passed since last update.

WordPressの固定ページテンプレートをフォルダで分ける

Posted at

WordPressの固定ページは通常、次の命名規則でファイルを作成します。

page-$pagename.php

例えば、companyというスラッグの固定ページなら

page-company.php

というファイル名になります。しかし例えば、companyの子ページとしてaboutを作成して、example.com/company/aboutにした場合でも、テンプレートファイル名は

page-about.php

となるため、大量の固定ページテンプレートを作る際に管理しにくくなります。そこで、これを次のようなテンプレートファイルを作れるようにします。

wp-content/themes/(テーマ名)/company/index.php - companyのテンプレート
wp-content/themes/(テーマ名)/company/about.php - company/aboutのテンプレート

page.phpの作り方

しくみとしては、本来の固定ページテンプレートであるpage.phpを次のようにします。

<?php
// テンプレートがあるかをチェック
$url = $_SERVER['REQUEST_URI'];
$url = explode('?', $url);
$url = $url[0];

$path = get_template_directory() . substr($url, 0, strlen($url) - 1) . '.php';
if (file_exists($path)) {
    include($path);
    exit();
}

// index.phpを付加して検索
$path = get_template_directory() . $url . '/index.php';
if (file_exists($path)) {
    include($path);
    exit();
}
?>

ここに、一般の固定ページ用のテンプレートを記述します

これで、先のようにテーマディレクトリの中にフォルダーを作ってテンプレートを配置すると利用できるようになります。従来通りのpage-$pagename.phpというテンプレートも利用できます(そちらの方が優先されます)。

10
16
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
10
16