Quantcast
Channel: Question and Answer » meta-query
Viewing all articles
Browse latest Browse all 36

Conditional posts in WP_query for search

$
0
0

I have a custom post type that im trying to limit results in search.

The CPT is a deal/coupon, with a start and end date for each of the deals.

What I’m trying to do is only show these posts in search:

  1. For non-recurring events….Show posts where the end date is today or after todays today.

OR

  1. For recurring events, limit it to show only events with an end date between today which does not exceed 7 days.

Each of these queries works perfectly on their own, but I cant combine them together…

function search_pre_get_posts( $query ) {

    if ( $query->is_search() && $query->is_main_query()   ) {  
        $recurring_count = am_get_recurring_count($post->ID);
        // Show non-recurring events with end date of today or after
        if ($recurring_count == 0){
            $currentdate =  date('Y-m-d');
            $query->set( 
                'meta_query',
                array(
                    'relation' => 'OR',
                    array(
                         'key' => 'am_enddate',
                         'compare' => '>=',
                         'value' => $currentdate,
                    ),
                    array(
                         'key' => 'am_enddate',
                         'compare' => 'NOT EXISTS',
                    )
                )
            );
            $query->set( 'orderby', 'meta_value' );
            $query->set( 'order', 'ASC' );
        } else {
           // Show recurring events with end date of today or after, that doesnt exceed 7 days.
            $currentdate =  date('Y-m-d');
            $enddate = strtotime(date('Y-m-d') . "+7 days");
            $enddate = date('Y-m-d',$enddate);
            $query->set( 
                'meta_query',
                array(
                    'relation' => 'OR',
                    array(
                         'key' => 'am_enddate',
                         'compare' => 'NOT EXISTS',
                    ),
                    array(
                        'relation' => 'AND',
                        array(
                             'key' => 'am_enddate',
                             'compare' => '>=',
                             'value' => $currentdate,
                        ),
                        array(
                             'key' => 'am_enddate',
                             'compare' => '<=',
                             'value' => $enddate,
                        )
                    )
                )
            );
            $query->set( 'orderby', 'meta_value' );
            $query->set( 'order', 'ASC' );
        }
    }
}
add_action( 'pre_get_posts', 'search_pre_get_posts' ); 

Viewing all articles
Browse latest Browse all 36

Trending Articles