WooCommerce products archive bug: Gaps from out of stock or hidden products
-
Hi everyone, I already solved this problem with a workaround but I thought I would post here as a bug report or just so people with the same problem can solve the issue themselves.
I am using Ajax Load More with a WooCommerce site via the [alm] shortcode and post_type=”product”. The problem is that there are gaps on the store as we have the option to hide out of stock products enabled. We also have some products set to catalog visibility = hidden.
These products still get loaded, but don’t appear. This means if you have 16 products per page but one is hidden, only 15 products show up.
Not a huge deal, but on mobile with 2 columns, having just one product looked like we’ve seen all of the products and were at the end of the line. That’s a poor user experience!
I’ve fixed this by excluding out of stock and hidden products during the query. I have two solutions: one for Ajax Load More and one for vanilla WordPress queries.
You can get the code at this Gist: https://gist.github.com/RadGH/332a447cdcdd76c84a48148d596ce5e6
Here is the solution specifically for Ajax Load More, from the above gist as of 7/12/2018:
/** * WooCommerce by default hides out of stock products AFTER the query. * This leaves gaps: If you have 16 products per page, but 1 of those products are out of stock, you only see 15. * This solution excludes out of stock products during the query, so you'll get the expected results even if some of the products are out of stock. * * @param $query * * @return WP_Query $query */ function rs_remove_out_of_stock_products_from_query( $query ) { if ( is_admin() ) return $query; // Only affect product archives // Consider using is_main_query(), although I wouldn't want out of stock products on secondary queries either!. if ( !$query->is_post_type_archive('product') ) return $query; // Set up meta query $meta_query = array(); // If a meta_query already exists, keep it -- require those condntions in addition to the stock query if ( !empty($query->get('meta_query')) ) { $meta_query = array( 'relation' => 'AND', $query->get('meta_query') ); } // Exclude out of stock products $meta_query[] = array( 'key' => '_stock_status', 'value' => 'outofstock', 'compare' => 'NOT IN' ); $query->set('meta_query', $meta_query); return $query; } add_action( 'pre_get_posts', 'rs_remove_out_of_stock_products_from_query', 20 );
- The topic ‘WooCommerce products archive bug: Gaps from out of stock or hidden products’ is closed to new replies.