• Resolved FriendlyWP

    (@mmcginnis)


    Hi, is there a way to exclude a page/post based on the value of a custom field? For instance if the meta_key ‘status’ is set to meta_value ‘inactive’, I don’t want that post displayed in search results.

    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Contributor pronskiy

    (@pronskiy)

    Hi @mmcginnis

    It’s definitely possible, but the solution may vary depending on your WordPress setup.
    For the simplest case, you don’t even need the Search Exclude plugin. Try adding following code to your functions.php:

    
    add_filter('pre_get_posts', function ($query) {
        $shouldApply =
            (!is_admin() || (defined('DOING_AJAX') && DOING_AJAX))
            && $query->is_search;
    
        if ($shouldApply) {
            $query->set('meta_query', array(
            'relation' => 'OR',
                array(
                    'key' => 'status',
                    'compare' => '!=',
                    'value' => 'inactive',
                ),
                array(
                    'key' => 'status',
                    'compare' => 'NOT EXISTS',
                    'value' => ''
                ),
            ));
        }
    
        return $query;
    });
    

    Please let me know if this worked for you. If not, feel free me to reach me out by email [email protected] and we’ll figure it out.

    Cheers!

    • This reply was modified 7 years, 8 months ago by pronskiy.
    Thread Starter FriendlyWP

    (@mmcginnis)

    Thank you so much @pronskiy for the quick reply – that worked perfectly!! Much appreciated.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Exclude based on custom field value?’ is closed to new replies.