Skip Navigation

[Closed] How to set View query filter for empty custom field

This support ticket is created 2 years, 12 months ago. There's a good chance that you are reading advice that it now obsolete.

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 2 years, 12 months ago.

Author
Posts
#2268107
Bildschirmfoto 2022-01-17 um 07.29.22.png

Hi, I have a custom field "revisit date" (type: date) and already created a view with upcoming dates, and one with past (due) dates. In order to make sure nothing escapes from our radar, I would need a third view that displays all posts where this field is empty (or not set at all?)

What is the "magic query" that gives me the desired result? I have tried several combinations but always end up with "No items found"

Thank you for your support!

#2268183

Nigel
Supporter

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

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

I don't think you can enter such a condition through the UI, you would need to use the API to modify the query arguments and manually set the filter to check if there is no entry for the revisit date field at all or if there is any empty entry for it.

So create your View to check for no revisit dates, don't include any filters, and then use the wpv_filter_query API filter to set the custom field queries.

Here's an example of the kind of code you would use:

function tssupp_filter_query($view_args, $view_settings, $view_id)
{
    if (in_array($view_id, array( 123 ))) { // Edit View ID(s) 

        $view_args['meta_query'] = array(
            'relation' => 'AND',
            array(
                'key' => 'wpcf-active',
                'value' => '1',
                'compare' => '='
            ), 
            array(
                'relation' => 'OR',
                array(
                    'key' => 'wpcf-revisit-date',
                    'compare' => 'NOT_EXISTS'
                ),
                array(
                    'key' => 'wpcf-revisit-date',
                    'value' => '',
                    'compare' => '='
                )
            )
        ) 
    }

    return $view_args;
}
add_filter('wpv_filter_query', 'tssupp_filter_query', 101, 3);

You'll need to edit the ID of the View this should be applied to, and also check the keys of your custom fields are correct (wpcf-active, and wpcf-revisit-date). (It is easier to add all of the filters in the same block of code than to modify the query where you already have some filters added.)

The topic ‘[Closed] How to set View query filter for empty custom field’ is closed to new replies.