Skip to content
Advertisement

How do I use tax_query and meta_query together?

I’ve got a custom post type called ‘jobs’ with a taxonomy called ‘job-status’. I’m trying to display a list of jobs with a certain tax term (job-complete) that haven’t got a report uploaded to them in a file ACF field type.

The first part works; I’ve got it returning a list of jobs with that taxonomy. I can’t get it working with the meta_query which is asking whether there’s a value in that field.

Code I have so far is;

$posts = get_posts(array(
    'post_type'         => 'jobs',
    'posts_per_page'        => -1,
    'meta_key'          => 'job_date',
    'orderby'           => 'meta_value',
    'order'             => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy' => 'job_status',
            'field' => 'slug',
            'terms' => array( 'complete' )
        ),
    ),
    'meta_query' => array (
      'relation' => 'AND',
        array (
          'key' => 'report_upload',
          'value' => '',
          'compare' => 'NOT EXISTS'
        )
    )
));

Advertisement

Answer

You are close! I think you only need to remove 'value' => '', from the meta_query so it looks like:

$posts = get_posts(array(
    'post_type'         => 'jobs',
    'posts_per_page'        => -1,
    'meta_key'          => 'job_date',
    'orderby'           => 'meta_value',
    'order'             => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy' => 'job_status',
            'field' => 'slug',
            'terms' => array( 'complete' )
        ),
    ),
    'meta_query' => array(
        array (
          'key' => 'report_upload',
          'compare' => 'NOT EXISTS'
        )
    )
));

Also don’t need the 'relation' => 'AND' as that is the default.

Had another thought where you may need something more like this:

$posts = get_posts(array(
    'post_type'         => 'jobs',
    'posts_per_page'        => -1,
    'meta_key'          => 'job_date',
    'orderby'           => 'meta_value',
    'order'             => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy' => 'job_status',
            'field' => 'slug',
            'terms' => array( 'job-complete' )
        ),
    ),
    // check for case where key does not exist or has an "empty" value (added a relation OR for this one)
    'meta_query' => array (
        'relation' => 'OR',
        array (
          'key' => 'report_upload',
          'compare' => 'NOT EXISTS'
        ),

        array (
          'key' => 'report_upload',
          'value' => '',
          'compare' => '='
        )
    )
));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement