LoginSignup
3

More than 5 years have passed since last update.

WordPressテーマを一般ファイルで使う

Last updated at Posted at 2018-04-01

2018-04-04
この記事の方法では<title>タグが「ページが見つかりませんでした」になるので、改訂版を投稿しました。


  • ブログ的記事投稿はWordPressを使っている
  • WordPressの管理画面が鬱陶しいから、静的ページは直接htmlファイルを使いたい
  • だけどヘッダ、フッタ、サイドバーはWordPressのテーマを流用したい

ていう要望があった。要するに、「固定ページは静的htmlファイルでつくりたい」て要望。

案外かんたんにできたので、作業記録をここに。前提として、.htaccessが使えること。

仕組み

  1. 静的htmlファイルをを作る。
  2. htaccessで静的ファイルへのアクセスをレンダリング用phpスクリプトへ集める

.htaccess

静的htmlファイルへのアクセスが後述するphpスクリプトへリライトされるようにする。

.htaccess
<IfModule mod_rewrite.c>
### WordPress 用 ####
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^index\.php$ - [L]
#####################

#### ハンドラファイル用 ####
# http://hoge.com/foo.htmlをhttp://hoge.com/foo/でアクセスさせる
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule . /render.php [L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . /render.php [L]
#######################
</IfModule>

要は、存在しないファイル・ディレクトリにアクセスがあった場合はWordPressに、それ以外はphpスクリプトへそれぞれ処理を任せるイメージ。

{REQUEST_FILENAME}\.html -fの部分はWordPressの記事とリンクの形式を合わせてみた。

phpスクリプト

render.phpを作成して、ドキュメントルートへ置く。静的htmlファイルへのアクセスはこのプログラムが処理する。

wp-blog-header.phpを読み込むことで、WordPress内の一連の関数が使えるようになることを利用する。

render.php

<?php
  require_once ('./wp-blog-header.php');

  $dir = dirname($_SERVER['REQUEST_URI']);
  if (strlen($dir) != 1) { # $dir == '/'の場合を考慮したけれどいらないかも
    $dir .= '/';
  }
  $file = basename($_SERVER['REQUEST_URI']);
  $filepath = dirname(__FILE__) . $dir . $file;

  $load_file = '';
  # htaccessの設定に合わせ拡張子を考慮
  if(file_exists($filepath . '.html'))
  { 
    $load_file = $filepath . '.html';
  }
  # ディレクトリへのアクセスはindexファイルを読み込む
  else if(file_exists($filepath))
  {
    $load_file = $filepath . '/index.html';
  }

  get_header();
?>

<div id="primary" class="content-area">
        <main id="main" class="site-main" role="main">

        <?php include($load_file); ?>

        </main><!-- .site-main -->

        <?php get_sidebar( 'content-bottom' ); ?>

</div><!-- .content-area -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

上記はTwenty Sixteenでのテーマでの例。テーマのpage.phpの中身を参考にした。コンテンツ部分だけ<?php include($load_file); ?>で静的htmlファイルを読み込ませている。

プログラムが多少雑だけれど、上記の基本を抑えればいろいろいじれるんじゃないかな。

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