Can I filter a wp query by custom taxonomy and the status of an ACF file field?

Viewed 338

I'm struggling a bit with this one. I've got a custom post type called jobs, which use a custom taxonomy to mark the job status; booked, complete, etc. Custom fields have been done with ACF.

What I'd like to do is show a list of jobs that have a certain job status, that don't yet have a file uploaded to them.

Example; Job status = complete. Report file field is empty

Code I've got so far is below. All it does at the moment is display 4x instances of the first CPT 'jobs' - the filters don't seem to make a difference.

<?php 

// get posts
$reports = array (
  'post_type' => 'jobs',
  'post_status' => 'inherit',
    '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'
        )
    )
);

if( $reports ): ?>

    <ul>

    <?php foreach( $reports as $reports ): 

        setup_postdata( $reports )

        ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?> (date: <?php the_field('start_date'); ?>)</a>
        </li>

    <?php endforeach; ?>

    </ul>

    <?php wp_reset_postdata(); ?>

<?php endif; ?>
1 Answers

All ACF fields within a custom post type can be accessed using the meta_query argument. For example, if wanted to return all 'post_type' => 'jobs', where the ACF custom field 'report_field' was empty, you could use the following code:

$args = array (
  'post_type' => 'jobs',
    'tax_query' => array (
      array (
        'taxonomy' => 'job_status',
        'field' => 'slug',
        'terms' => array( 'complete' )
      ),
    ),
    'meta_query' => array (
      'relation' => 'AND',
        array (
          'key' => 'report_field',
          'value' => "",
          'compare' => "="
        )
    )
);

If you would prefer showing jobs where report_field doesn't exist, you could change the 'compare' => "=" argument to 'compare' => "NOT EXIST"

Another pit-fall you may come across is the post_status, so be sure to make sure your post_status for your custom_post_type is published. Otherwise, you may need to use a different argument for your post_status, such as:

'post_status' => 'inherit'
Related