LoginSignup
1
2

More than 5 years have passed since last update.

Custom Field Templateプラグインで固定ページのテンプレート選択がプレビューに適用されない件

Last updated at Posted at 2016-10-06

WordPressの人気プラグインで、カスタムフィールドを簡単に実装できる「カスタムフィールドテンプレート(Custom Field Template)」というものがあります。
↓これ
https://ja.wordpress.org/plugins/custom-field-template/

以下の出来事があり困ったので、報告と解決方法を。

  1. WordPress 4.6.1を使用中(ここは検証していないので、他のバージョンでもそうなるかもだし、同じ環境でもならないかも)
  2. カスタムフィールドテンプレート(Custom Field Template)プラグインをインストール
  3. 固定ページの編集画面でページテンプレートを「デフォルト以外のテンプレート」を選択している
  4. 上記の状態で「プレビュー」をクリックしてページを開くと、上記3.で選択したテンプレートが適用されずに開いてしまう。

という困ったことが起きて泣きそうに・・・

解決方法

functions.phpに以下のコードを書くことで解決しました。

functions.php
add_filter('get_post_metadata',function($return, $post_id, $meta_key, $single){
  global $post;
  $page_template_key='_wp_page_template';
  if (($meta_key==$page_template_key) && isset($post) && $post->ID == $post_id && is_preview()){
    //プレビュー状態のとき
    global $wpdb;
    $return=$wpdb->get_var($wpdb->prepare('SELECT meta_value FROM $wpdb->postmeta WHERE `meta_key` = %s AND `post_id` = %d',$page_template_key,$post_id));
  }
  return $return;
},20,4);

やっていること

カスタムフィールドテンプレートの機能として、固定ページの編集中に「プレビュー」したときにも、カスタムフィールド入力値がプレビュー画面に反映されるように、get_post_metaにフィルターかけているのですが、どうやら、その処理のなかで、固定ページで選択されているページテンプレートの値も一緒に処理されちゃうみたいなのです。
なので、そのフィルターの後から、無理やりデフォルトテンプレートを書き戻す処理を書きました。

正直、こちらのプラグインを普段あまり使わないもので、これが正しい解決方法なのか自信ありません。

ひょっとしたらプラグインの設定レベルで解決できたりするのでは・・・とか思いつつ、とりあえずシェアさせていただきました。

あと、かなり強引な処理なので使用できる局面は限定的だと思います。
例えば、固定ページ選択を変更して保存前にプレビューしたいなどのときは、うまく動作しないかも。

補足

PHPのバージョンが古い(5.3以前かな?)人は以下のコードを

functions.php
function my_get_preview_postmeta($return, $post_id, $meta_key, $single){
  global $post;
  $page_template_key='_wp_page_template';
  if (($meta_key==$page_template_key) && isset($post) && $post->ID == $post_id && is_preview()){
    //プレビュー状態のとき
    global $wpdb;
    $return=$wpdb->get_var($wpdb->prepare('SELECT meta_value FROM $wpdb->postmeta WHERE `meta_key` = %s AND `post_id` = %d',$page_template_key,$post_id));
  }
  return $return;
}
add_filter('get_post_metadata','my_get_preview_postmeta',20,4);
1
2
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
2