Skip Navigation

[Resolved] View selecting posts missing a custom field

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

This topic contains 1 reply, has 2 voices.

Last updated by Nigel 8 months, 1 week ago.

Author
Posts
#2698028
Screenshot 2024-05-15 at 4.04.23 PM.png

I'd like to create a view that selects posts that do not have a row in the database for a specific custom field. Is this possible? I tried a filter that looks for a constant that is empty for the custom field, but it's not working ... I assume because the posts in question do not have that row in the database (wp_postmeta table). I'm attaching a screenshot of the query filter that is not working for this.

#2698104

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi there

You need the EXISTS test, but it's not possible to add that using the UI, you will need to use the API hook wpv_filter_query to modify the generated query to include such a condition.

See the WordPress documentation for WP_Query about using EXISTS to test for the presence of a specified meta_key: https://developer.wordpress.org/reference/classes/WP_Query/#custom-field-post-meta-parameters

The View you create is essentially a user-friendly UI for generating such queries, and so when modifying the generated queries using the Views API you will work with exactly the same query parameters.

You can see an example of using the wpv_filter_query here: https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query

#2698203

Thanks Nigel, with your help I was able to come up with this function which seems to do the trick:

// modify the view query so that it only returns posts without the '_yoast_wpseo_primary_category' meta key
add_filter( 'wpv_filter_query', 'nm_prim_cat_filter_query', 101, 3 );
function nm_prim_cat_filter_query( $view_args, $view_settings, $view_id ) {
if ( in_array( $view_id, array( 85757 ) ) ) { // Edit View IDs
$view_args['meta_key'] = '_yoast_wpseo_primary_category';
$view_args['meta_compare'] = 'NOT EXISTS';
}
return $view_args;
}