1

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

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.

  • You're good! That worked. Should I be concerned that it's affecting any other parts of my site if you're unsure if that's 100% the correct code for my search template? Are there any other files you'd want to see to be sure? If not, I appreciate your help! – Abby G. Oct 19 '17 at 15:29
  • For 99% of the themes, this is what you need. And since it works, all is OK. Code is made to affect only search results page, so it will not mess with other stuff. – Milan Petrovic Oct 19 '17 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.