Search code examples
ajaxwordpressmeta-query

How to get all posts if post don't have specific meta key?


I'm trying to add post filters based on specified post metadata. Filters works great but when I select "All types" filter doesn't reset and no posts are displayed.

HTML:

<select name="typefilter">
<option value="">All types</option>
<option value="type1">Type 1</option>
<option value="type2">Type 2</option>
<option value="type3">Type 3</option>
</select>

<button>Apply filters</button>

PHP:

if( isset( $_POST['typefilter'] ) ) {
    $args['meta_query'][] = array(
        'key' => 'custom_type',
        'value' => $_POST['typefilter'],
        'compare' => '='
    );
}

Solution

  • Your if condition only checks that the typefilter key exists in $_POST but not whether it's empty or not. WordPress then tries to fetch posts that have a custom field called custom_type with an empty value. WordPress fails to find posts that meet that criteria, hence the reason why you're not getting any results.

    Within your if condition, check that the typefilter key is set and that it's not empty:

    // User wants to filter posts by type
    if( isset( $_POST['typefilter'] ) && ! empty( $_POST['typefilter'] ) ) {
        $args['meta_query'][] = array(
            'key' => 'custom_type',
            'value' => $_POST['typefilter'],
            'compare' => '='
        );
    }