2018/04/09 全体的にリファクタして書き直しました
前回の記事だとtitleタグがセットできないので、タブに「ページが見つかりませんでした」と表示されてしまった
タイトルもセットできるように改修したのが今回の記事。
.htaccess
ここは前回と同じ
.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]
# ちなみにfoo.htmlでそのままアクセスさせたいときは下記
# RewriteRule \.html$ /handler.php [L]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . /render.php [L]
#######################
</IfModule>
hoge.html
(一般ファイル)
拡張子は.html
だけれど、ファイルの先頭でPHPスクリプトとして扱いタイトル用の変数をセットしておく
hoge.html
<?php $_title = 'テスト' ?>
<h1>hello, world!</h1>
render.php
document_title_parts
フックにタイトルをセットする関数を登録するのがミソ。
render.php
<?php
$dir = dirname($_SERVER['REQUEST_URI']);
if ($dir != '/') {
$dir .= '/';
}
$file = basename($_SERVER['REQUEST_URI']);
$filepath = $_SERVER['DOCUMENT_ROOT'] . $dir . $file;
$static_file = '';
if(is_dir($filepath))
{
$static_file = $filepath . '/index.html';
}
else if(file_exists($filepath . '.html')) // URLに.htmlを含めたいときは、$filepathだけでいい
{
$static_file = $filepath . '.html';
}
ob_start(); // 出力先をここからバッファに向ける
include($static_file); // $_titleの取得もここで
$_contents = ob_get_contents(); // バッファのコンテンツを保持
ob_end_clean(); // バッファを破棄
// original フラグがあればそのまま出力
if(isset($_original) && $_original) {
echo $_contents;
return;
}
require_once ('./wp-blog-header.php');
add_filter( 'document_title_parts', function ($title) use ($_title) {
$title['title'] = $_title;
return $title;
}
);
get_header();
?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php include($load_file); ?>
</main><!-- .site-main -->
<?php echo( $_contents ); /* コンテンツ出力 */ ?>
</div><!-- .content-area -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
function ($title) use ($_title) { ... }
の書き方は今回調べて初めて知った。use
オプションをこのように使うと、定義元のスコープを引き継いで変数を関数に渡せる。
$_original
はおまけでつけてみた。WordPressのテンプレを使わないでそのまま静的ファイルを表示したいときは、hoge.html
の先頭とかに<?php $_original = true; ?>
を入れるだけで対応可能になる。