I’m really new to php editing but I’m trying to learn. My woocommerce products that are set to “hidden” under catalog visibility are still showing up under search results. How do I keep hidden products out of my search results? I found this thread (WP_Query: Exclude hidden products from WooCommerce product list) and tried adding the below code mentioned at the bottom of the thread (I’m using Woocommerce 3.2.1) to my child theme’s functions.php file. It gave me the white screen of death and this error:

Parse error: syntax error, unexpected ‘=>’ (T_DOUBLE_ARROW).

<?php
/*
Code to remove hidden woocommerce products from being displayed in a site search
*/
'tax_query' => array(
                  array(
                        'taxonomy' => 'product_visibility',
                        'field'    => 'name',
                        'terms'    => 'exclude-from-catalog',
                        'operator' => 'NOT IN',

                  )
              ) 

Appreciate help in what I’m doing wrong. Thanks!

2 Answers
2

This code can’t be added anywhere you want, and it can’t be added to functions.php or any other php file like this. This is a element for the array used to create the WordPress query object. It has to be added via WP_Query class or get_posts and query_posts functions, or via the filter to modify the main page query.

But, without knowing more on how your search template works, there is no way to provide the help with this. If you work with classic search template, this is the code that will apply the taxonomy filter you need to use, and you can add this to the functions.php:

add_action('pre_get_posts', 'wpse_187444_search_query_pre');

function wpse_187444_search_query_pre($query) {
    if ($query->is_search() && $query->is_main_query()) {
        $tax_query = $query->get('tax_query', array());

        $tax_query[] = array(
            'taxonomy' => 'product_visibility',
            'field'    => 'name',
            'terms'    => 'exclude-from-catalog',
            'operator' => 'NOT IN',
        );

        $query->set('tax_query', $tax_query);
    }
}

But, this might not work for you, it depends on your search template and the way search results are queried.

Leave a Reply

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