LoginSignup
1
0

More than 5 years have passed since last update.

【改訂版】WordPressテーマを一般ファイルで使う

Last updated at Posted at 2018-04-03

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; ?>を入れるだけで対応可能になる。

参考

1
0
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
1
0