Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all articles
Browse latest Browse all 8245

JustRunLah on "How to query custom post types with mixed AND & OR statements for custom fields"

$
0
0

I have a custom post type "events" which includes the custom fields "is_premium" (which is a true/false) and "premium_expiry_date" which is a date picker.

On my front end, I want to have "events" which are premium and their premium_expiry_date has not passed to be displayed on the top of the results.

I have managed to do half of that by WP_Query querying "events" for which the is_premium==true && premium_expiry_date>$today (my code shown below). I pull them successfully in a table which appears ton top of my page.

My problem is with displaying the rest, and avoiding double posts.

Essentially, I would need a query like [ is_premium==false OR (is_premium==true AND premium_expiry_date<$today ) ] but I know that AND and OR cannot be mixed in one WP_Query.

I have tried to go into using $wpdb but with no luck (I am lacking SQL knowledge...)

My question is, could somebody either help me with how to syntax this using $wpdb, or direct me to a different path for achieving my desired result?

// This is the code I use to show the premium events which have not occurred yet,
        // and their premium date has not passed
        $today = date('Ymd');
        $args = array(
        'post_type' => 'event',
        'orderby'   => 'event_date',
        'meta_key'  => 'event_date',
        'order' => 'ASC',
        'relation' => 'AND',
        'meta_query' => array(

                array(
                'key'       => $the_key, //I read this from a _GET value. It resembles another custom field
                'compare'   => 'LIKE',
                'value'     => $current_region->name, //filter based on current region
                ),

                array(
                'key'       => 'event_date',
                'compare'   => '>=',
                'value'     => $today
                ),

                array(
                'key'       => 'is_premium',
                'compare'   => '==',
                'value'     => 1
                ),

                array(
                'key'       => 'premium_expiry_date',
                'compare'   => '>=',
                'value'     => $today
                    ),

                ),
            );

    ?>

    <?php $the_query = new WP_Query( $args ); ?>

    <?php if( $the_query->have_posts() ): ?>

    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

... END

[Moderator Note: Please post code & markup between backticks or use the code button. Your posted code may now have been permanently damaged by the forum's parser.]

Thanks a lot in advance


Viewing all articles
Browse latest Browse all 8245

Trending Articles