LoginSignup
2
2

WordPressでACFの値がプレビュー画面に表示されない問題の解決方法

Last updated at Posted at 2024-02-04

原因

WordPressでは、投稿やページの編集履歴をリビジョンとして保存します。ACFを使用してフィールドの値を取得しようとすると、プレビュー時にACFが参照する投稿IDが編集中の投稿ではなく、リビジョン(または自動保存されたバージョン)になっている為、値の代わりにfalseが返されることがあります。

解決策

この不具合の対策として、プレビュー時に正しい投稿IDをACFに渡すためのカスタムコードをfunctions.phpに追加します。

index.html
function fix_post_id_on_preview($null, $post_id) {
    if (is_preview()) {
        // プレビュー時は現在のポストIDを返す
        return get_the_ID();
    } else {
        // プレビューでない場合は、渡された$post_idを検証して返す
        $acf_post_id = isset($post_id->ID) ? $post_id->ID : $post_id;
        if (!empty($acf_post_id)) {
            return $acf_post_id;
        } else {
            return $null;
        }
    }
}
add_filter('acf/pre_load_post_id', 'fix_post_id_on_preview', 10, 2);
2
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
2
2