I am using custom statuses for my woocommerce products using the following code:
add_action( 'init', 'my_custom_status_creation' );
function my_custom_status_creation(){
$status_keys = array(
'retired'=>'Retired',
'sold-ooaks'=>'Sold OOAKs',
'consignment'=>'Sent to Consignment',
'pickbox'=>'Out on Pickbox'
);
foreach ($status_keys as $status_key=>$label){
$status_label = _x( $label, 'post', 'woocommerce' );
register_post_status( $status_key, array(
'label' => $status_label,
'public' => true,
'exclude_from_search' => true,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( $status_label.' <span class="count">(%s)</span>', $status_label.' <span class="count">(%s)</span>'),
) );
}
}
However, when this code snippet is being used, the native function of being able to exclude out-of-stock products from search results no longer works (this option can be found woocommerce -> settings -> products -> inventory and checking "Hide out of stock items from the catalog").
I've tested this with other plugins/code deactivated, but out-of-stock products continue to appear in my search results.
I also thought that
'exclude_from_search' => true,
would exclude those results from search, but it doesn't seem to work either.
I also tried:
add_action( 'pre_get_posts', 'misha_hide_out_of_stock_in_search' );
function misha_hide_out_of_stock_in_search( $query ) {
if( $query->is_search() && $query->is_main_query() ) {
$query->set( 'meta_key', '_stock_status' );
$query->set( 'meta_value', 'instock' );
}
}
This does prevent out-of-stock products, but it also prevents other search results (ie posts, pages, events) from appearing on the search archive.
How can I make sure that out-of-stock products do not appear in the search results while still getting non-products results such as posts/events/pages/etc. ?
You could try condition your code to only apply to "product" queries: