Woocommerce – Hide ‘Hidden’ products from site search

This problem has been around for a while, and none of the resources that I could find online gave me any sort of idea  how it could be done. The worst result that I found was this one, where a representative of WooThemes themselves said that this couldn’t be done… That led me to believe that they were right, and it really couldn’t be done. Admittedly, that answer was given in 2012, so it’s a few years past now, so I wanted to see if anything had changed since then.

That got me thinking – if I could control the search query, why couldn’t I filter out the values? After all, it’s only a meta field, and I know that I can filter those for searches.

So I looked into it, and I came up with this small bit of code that actually works.

add_action ('pre_get_posts', 'catacuastic_hide_hidden_products');

function catacaustic_hide_hidden_products ($query) {
    if (is_search () && !is_admin ()) {
        $query->query_vars ['meta_query'] = array (
            'relation' => 'OR',
            array (
                'key' => '_visibility',
                'compare' => '!=',
                'value' => 'hidden'
            ),
            array (
                'key' => '_visibility',
                'compare' => 'NOT EXISTS'
            )
        );
    }
};

What I’ve done there is give it two directives, and said that if either of them don’t fit, don’t include that record. First, I search to see if the visibility value is not set as ‘hidden’. Second, I check if the visibility value is actually there, and if it’s not there (remember only products have this set) then include the record.

So, the “solution” from Woo themselves is indeed now wrong, and we can filter out hidden products from the standard WordPress search!

Leave a Reply

Your email address will not be published. Required fields are marked *