1

I'm trying to figure out why this query is not working, as it seems like it should be very straightforward. Basically, I'm querying for both standard posts of certain categories (and excluding another) and posts of the event custom post type after the current date. As it stands, I can only successfully query one or the other, i.e. posts by category or events after current date, but not both, together in a single query—what am I doing wrong here? I'm hoping I don't have to set up two separate queries and combine the results (?) Thanks for any direction.

    $catslugs = array('home-slideshow');
    $catids = get_cats_by_slug($catslugs);

    $args = array(
        'ignore_sticky_posts' => true,
        'post_type' => array('post', 'event'),
        'orderby' => 'date',
        'order' => 'DESC',
        'posts_per_page'    =>  10,
        'category__not_in' => $catids,
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'fields' => 'slug',
                'terms' => array('slug-1', 'slug-2')
            )
        ),
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'event_start_date',
                'type'    => 'DATE',
                'value'   => current_time('Ymd'),
                'compare' => '>=',
            ),
        )
    );

(As the name suggests, the function above get_cats_by_slug simply returns category IDs by slug.)

  • 1
    Probably because the post doesn't have this meta and the event doesn't have the categories.. You can do it with custom MySQL query or with 2 separate queries. – Shibi Jul 2 '18 at 22:37
  • @Shibi thanks for the response- that's what I figured but wasn't sure; is it possible to somehow state in the query "if this meta_value is set, then..."? Otherwise, is it considered bad practice to query twice and merge and/or server intensive? I haven't had to do that before in WP, although this is a rather unique sort of query, I suppose. – nickpish Jul 2 '18 at 22:42
  • You can use the 'relation' => 'OR' to check if not exists the meta or the category at first step so it will pass but it can be a problem if you have events without the date. And the query will be a complex one so maybe it will be better to do 2 separate and then merge the arrays. – Shibi Jul 2 '18 at 22:48
  • Ok, thanks @Shibi; guess I'll go the combined route after all. – nickpish Jul 2 '18 at 23:03
  • 2
    tax_query' => array( is missing a ' at the beginning. – Jacob Peattie Jul 3 '18 at 1:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.