Фильтр расписания с ACF

Мне нужно создать WP_Query, который фильтрует сообщения по некоторым расширенным настраиваемым полям. Следующие пункты описывают необходимые функции:

  • Сегодня больше start_date и меньше end_date.
  • Если сегодня 'start_date', проверьте, больше ли время, чем 'start_time'.
  • Если сегодня - «дата_кончания», текст, если время меньше, чем «время_кончания».
  • Получить только первое сообщение, упорядоченное по настраиваемому полю «приоритет».

Я изо всех сил пытаюсь построить типичную клаузулу WHERE, например:

SELECT * FROM x WHERE (
  ( 'start_date' < today AND 'end_date' > today )
  OR
  ( 'start_date' = today AND 'start_hour' < now )
  OR
  ( 'end_date' = today AND 'end_hour' > now )
)
ORDER BY y
LIMIT 0,1;

Я некоторое время думал об этом, я думал, что это возможно, вложив meta_queries в аргументы WP_Query ... Не сработало (см. Аргументы ниже).

$now_date = date('Ymd');
$now_time = date('Hi');
$args = array(
    'post_type'         => 'post',
    'cat'               => 4, /* Bulletin */
    'posts_per_page'    => 1,
    'post_parent'       => 0,
    'post_status'       => 'publish',

    'meta_query' => array(
        'relation' => 'OR',
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key'       => 'bu_from',
                'compare'   => '<',
                'value'     => $now_date,
                'type'      => 'NUMERIC'
            ),
            array(
                'key'       => 'bu_to',
                'compare'   => '>',
                'value'     => $now_date,
                'type'      => 'NUMERIC'
            )
        ),
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key'       => 'bu_from',
                'compare'   => '=',
                'value'     => $now_date,
                'type'      => 'NUMERIC'
            ),
            array(
                'key'       => 'bu_from_time',
                'compare'   => '<=',
                'value'     => $now_time,
                'type'      => 'NUMERIC'
            )
        ),
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key'       => 'bu_to',
                'compare'   => '=',
                'value'     => $now_date,
                'type'      => 'NUMERIC'
            ),
            array(
                'key'       => 'bu_to_time',
                'compare'   => '>=',
                'value'     => $now_time,
                'type'      => 'NUMERIC'
            )
        )
    ),
    'meta_key'          => 'bu_priority',
    'orderby'           => 'meta_value',
    'order'             => 'ASC'
);

ЗАПРОС, который игнорирует все мета_запросы:

/* Taken from var_dump($the_query); */
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
  FROM wp_posts
    INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
    INNER JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
  WHERE 1=1
    AND wp_posts.post_parent = 0
    AND ( wp_term_relationships.term_taxonomy_id IN (4) )
    AND wp_posts.post_type = 'post'
    AND ((wp_posts.post_status = 'publish'))
    AND (wp_postmeta.meta_key = 'bu_priority' )
  GROUP BY wp_posts.ID
  ORDER BY wp_postmeta.meta_value ASC
  LIMIT 0, 1
;

person jdev    schedule 20.07.2015    source источник


Ответы (1)


После обсуждения с руководством, что именно нам нужно ... Я изменил всю логику, которая здесь задействована.

    <!-- START: BULLETIN -->
    <?php
        $args = array(
            'post_type'         => 'post',
            'cat'               => 4, /* Bulletin */
            'posts_per_page'    => -1,
            'post_parent'       => 0,
            'post_status'       => 'publish',

            'orderby'           => 'ID',
            'order'             => 'DESC'
        );

        $the_query = new WP_Query( $args );

        if ( $the_query->have_posts() ) :
            // Start the Loop.
            $added_cnt = 0;
            $now = array( 'date' => date('md'), 'day' => date('N') );
            $bulletins = array(
                '1' => array(),
                '2' => array(),
                '3' => array(),
                '4' => array(),
                '5' => array()
            );
            while ( $the_query->have_posts() ) : $the_query->the_post();

                if (
                    /* Scheduled by day and month */
                    (
                        ( get_field('bu_schedule_by') == '1' )
                        &&
                        ( get_field('bu_start_month').get_field('bu_start_day') <= $now['date'] )
                        &&
                        ( get_field('bu_end_month').get_field('bu_end_day') >= $now['date'] )
                    )
                    ||
                    /* Scheduled by day of the week */
                    (
                        ( get_field('bu_schedule_by') == '2' )
                        &&
                        ( in_array( $now['day'], get_field('bu_days_to_be_seen') ) )
                    )
                ) {
                    $bulletins[ get_field('bu_priority') ][ get_the_ID() ] = array();
                    $bulletins[ get_field('bu_priority') ][ get_the_ID() ][ 'title' ] = get_the_title();
                    $bulletins[ get_field('bu_priority') ][ get_the_ID() ][ 'subtitle' ] = get_field('bu_subtitle');
                    $bulletins[ get_field('bu_priority') ][ get_the_ID() ][ 'image' ] = get_field('bu_image');
                    $bulletins[ get_field('bu_priority') ][ get_the_ID() ][ 'content' ] = get_the_content();
                    $added_cnt++;
                }
            endwhile;

            $bulletin = array();
            $bu_priority = 1;
            while ( ( $added_cnt > 0 ) && ( count($bulletin) == 0 ) ) {
                if ( count($bulletins[$bu_priority]) > 0 ) {
                    $bulletin = reset($bulletins[$bu_priority]);
                }
                $bu_priority++;
            }

            $bu_image = $bulletin['image'];
            echo '
                <div class="section group section_opener custom_bulletin" style="margin-top: 4px; margin-bottom: 4px; padding: 0 !important;">
                    <div id="xmas_bg" class="col span_4_of_16"'.( !empty($bu_image) ? ' style="background-image: url('.$bu_image['url'].'); background-position: 50%; background-repeat: no-repeat; margin: 40px 0; height: 178px;"' : '' ).'></div>
                    <div id="xmas_title" class="col span_4_of_16" style="">
                        '.( $bulletin['title'] != '' ? '<h1 style="font-size: 28px; font-weight: 700;">'.$bulletin['title'].'</h1>' : '' ).'
                        '.( $bulletin['subtitle'] != '' ? '<h2 style="font-size: 23px; color: #c94446; font-weight: 300; margin-top: -8px;">'.$bulletin['subtitle'].'</h2>' : '' ).'
                    </div>
                    <div class="col span_1_of_16"></div>
                    <div id="xmas_copy" class="col span_6_of_16" style="padding: 80px 0; font-size: 14px !important;">
                        '.$bulletin['content'].'
                    </div>
                    <div class="col span_1_of_16"></div>
                </div>
            ';

        endif;
    ?>
    <!-- END: BULLETIN -->
person jdev    schedule 20.07.2015