0
0

More than 3 years have passed since last update.

Wordpressでpre_get_postsで記事を取得する際ACFの繰り返しフィールド内のデータを条件に加える方法

Posted at

例えば繰り返しフィールド(event)で、開催日(start)、終了日(finish)をカスタムフィールドで設定して
現在日付がそれらの間だった時の記事を取得させる場合

query.php
function change_posts_per_page($query) {
    //管理画面のメインクエリーとメインクエリーじゃないときは処理しない
    if (is_admin() || !$query->is_main_query()) return;

    // 特定のクエリにて処理
    if ($query->is_category() || $query->is_tag() || $query->is_search()) {
        // 20件取得
        $query->set('posts_per_page', 20);
        // 本日日付取得
        $today = date_i18n('Ymd');
        // SQLを変更させるフラグとして設置
        $query->set('wildcard_meta_key',true);
        $query->set(
            'meta_query', array(
                array(
                    'key' => 'event_%_start',
                    'value'   => $today,
                    'compare' => '<='
                ),
                array(
                    'key' => 'event_%_finish',
                    'value'   => $today,
                    'compare' => '>='
                ),
                'relation'=>'AND'
            )
        );

    }


}
add_action( 'pre_get_posts', 'change_posts_per_page' );

// リピータ部分のワイルドカード対応
function my_posts_where_wildcard( $where, $query ) {
    if ( $query->get( 'wildcard_meta_key' ) ) {
        $where = str_replace( 'meta_key =', 'meta_key LIKE', $where );
    }
    return $where;
}
add_filter( 'posts_where', 'my_posts_where_wildcard', 10, 2 );

とfunctions.php系に記載する。
wildcard_meta_keyを設定しているのは複数meta_query系処理を追加させた場合に、
繰り返しフィールドを対象としないものを除外させるため。

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