Powered by Blogger.

How to query posts which a meta key does not exist or is false


In my client’s site, there’s a post type of job. All job posts created by a script that parses the XML file. When using WordPress’ API wp_insert_post to insert post it won’t add all custom meta which added by ACF automatically.

That’s to say if you don’t open a job post and save in backend with then all custom fields added by ACF are missing. And now the client wants filter posts by an ACF field, there are two ways to do fix this issue.


1. Update the script which parses XML file also insert custom fields when inserting jobs post. And set query vars to add meta_key before getting posts.


function waytwowp_filter_by_custom_fields( $query ) {
    $query->set( 'meta_key', 'community_job');
    $query->set( 'meta_value', 0);
    
    return $query;
}
add_action( 'pre_get_posts', 'waytwowp_filter_by_custom_fields' );

/*community_job is the field name which added in ACF*/

Why need to insert custom fields when inserting jobs post? Because the above method will fail if a post hasn’t meta_key of ‘community_job’.

2. The second way, we just need to update the pre_get_posts filter to query all posts in which a meta key does not exist or is false.

function waytwowp_filter_by_custom_fields( $query ) {
    $meta_query = array(
                       'relation' => 'OR',
                        array(
                         'key' => 'community_job',
                         'compare' => 'NOT EXISTS'
                        ),
                        array(
                         'key' => 'community_job',
                         'value' => 0
                        )
                    );
    $query->set( 'meta_query', $meta_query );
    
    return $query;
}
add_action( 'pre_get_posts', 'waytwowp_filter_by_custom_fields' );

/*community_job is the field name which added in ACF*/

No comments