If you have excluded out of stock products and you still see them in the search results, there’s probably an error concerning the relationships in your database. This may occur, for example, after using importing tools etc.
Since the release of Woocommerce 3.0, the product visibility is now handled by the product_visibility
custom taxonomy. Some importing scripts may ignore this change and this raises issues.
Solution 1 – fix database relationships (recommended)
To fix database relationships, you have to fire the following PHP script. Run this script only once!
// Fire this code only once!!! Remove this code after fixing product visibility add_action('admin_footer', function(){ global $wpdb; $wpdb->hide_errors(); $term_id = wc_get_product_visibility_term_ids()['outofstock']; // STEP 1 | Wipe all current relationships related to outofstock $wpdb->delete( $wpdb->term_relationships, array( 'term_taxonomy_id' => $term_id ), array( '%d' ) ); // STEP 2 | Get all products with stock status "outofstock" $ids = wc_get_products( array( 'status' => array( 'publish' ), 'limit' => - 1, 'stock_status' => 'outofstock', 'return' => 'ids' ) ); // STEP 3 | Hide these products by adding correct term relationships if ( ! empty( $ids ) && is_array( $ids ) ) { $wpdb->query( 'START TRANSACTION' ); for ( $i = 0; $i < count( $ids ); $i ++ ) { $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $ids[ $i ], 'term_taxonomy_id' => $term_id, 'term_order' => 0 ), array( '%d', '%d', '%d' ) ); if ( $i % 100 == 0 ) { $wpdb->query( 'COMMIT' ); $wpdb->query( 'START TRANSACTION' ); } } $wpdb->query( 'COMMIT' ); } });
How to fire this script?
By child theme using functions.php file
Open the functions.php
in your child theme and add the code at the end of the file. Refresh the admin dashboard to execute the script and remove the code from the functions.php
file.
By the Code Snippets plugin
Install the Code Snippets plugin and apply the code as a snippet. Refresh the admin dashboard to execute the script and remove the snippet afterwards.
After the code is executed, go to WooCommerce
> FiboSearch
> Indexer
and rebuild the index.
Solution 2 – use the stock status from wp_postmeta
It may happen that the import or synchronization tool runs too frequently for the fixer to fix the problem permanently. In this case, you can switch FiboSearch to use the stock status stored in the wp_postmeta
table. You can do it with the following code snippet:
add_filter( 'dgwt/wcas/indexer/source_query/where/exclude_outofstock', function( $where ) { global $wpdb; $where = " AND ( posts.ID NOT IN ( SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_stock_status' AND meta_value = 'outofstock' ))"; return $where; } );
ⓘLearn how to add this snippet to your WordPress.
Go to WooCommerce
> FiboSearch
> Indexer (tab)
and rebuild the search index. Wait for this process to finish.