Posted on

Hidden WooCommerce products in search

Relevanssi by default shows hidden WooCommerce products in the search results. It is quite easy to make Relevanssi not to display hidden products in the results. The best way is to unindex the products, so that they don’t appear in the index at all.

How that is done, depends on the version of WooCommerce you’re using.

WooCommerce 3

WooCommerce 3 uses taxonomy terms to handle the visibility.

add_filter('relevanssi_do_not_index', 'rlv_wc3_hidden_filter', 10, 2);
function rlv_wc3_hidden_filter($block, $post_id) {
  if (has_term('exclude-from-catalog', 'product_visibility', $post_id)) $block = true;
  if (has_term('exclude-from-search', 'product_visibility', $post_id)) $block = true;
  if (has_term('outofstock', 'product_visibility', $post_id)) $block = true;
  return $block;
}

This code, placed in the theme functions.php, will unindex products that set to be excluded from the catalog, excluded from search or that are out of stock. If you want to keep out of stock items in the search results, just remove that line from the function.

The changes take effect once you rebuild the index. Do note that if you change the product visibility without saving the post, the changes won’t be reflected in the index until the post is saved or the index is otherwise rebuilt.

WooCommerce 2

Earlier versions of WooCommerce use a custom field to control the visibility.

add_filter('relevanssi_do_not_index', 'rlv_wc2_hidden_filter', 10, 2);
function rlv_wc2_hidden_filter($block, $post_id) {
  $visibility = get_post_meta($post_id, '_visibility', true);
  if ("catalog" == $visibility) $block = true;
  if ("hidden" == $visibility) $block = true;
  return $block;
}

The visibility setting has four values: “visible”, “catalog”, “search” and “hidden”. “Visible” means it’s visible everywhere, “hidden” means it’s hidden everywhere. “Catalog” means the product is visible in shop pages and category pages, but not search results. “Search” means the product is visible in search results, but not in the shop page or category pages. This function matches that definition.

Again, you need to rebuild the index to see the effects from this.