Woocommerce按库存排序,将含no2.png图的商品后置展示
Solution: Combine Stock Status Sorting with Placeholder Image Prioritization
Got it, let's build on your existing inventory sorting logic to push those products using the no2.png placeholder image to the very end. Here's how you can adjust your code in functions.php to make this work seamlessly:
Step-by-Step Code Adjustment
Replace or update your existing stock-sorting function with this combined logic:
add_action( 'woocommerce_product_query', 'custom_product_sort_by_stock_and_placeholder' ); function custom_product_sort_by_stock_and_placeholder( $query ) { // Only target frontend shop pages, not admin if ( ! is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() || is_product_tag() ) ) { // Keep your core stock status sorting $query->set( 'meta_key', '_stock_status' ); // Add our custom image-based sort to the orderby array $query->set( 'orderby', array( 'meta_value' => 'ASC', // Instock → Outofstock 'custom_placeholder_sort' => 'ASC' // Non-placeholder → Placeholder ) ); // Ensure we're pulling in thumbnail metadata for our sort check $existing_meta_query = $query->get( 'meta_query', array() ); $existing_meta_query[] = array( 'key' => '_thumbnail_id', 'compare' => 'EXISTS', ); $query->set( 'meta_query', $existing_meta_query ); // Hook in our custom SQL clause for image sorting add_filter( 'posts_orderby', 'custom_placeholder_orderby_clause', 10, 2 ); } } function custom_placeholder_orderby_clause( $orderby, $query ) { global $wpdb; // Only apply this if our custom sort is active if ( isset( $query->query_vars['orderby']['custom_placeholder_sort'] ) ) { // Add a CASE statement to flag products using no2.png $orderby = " {$wpdb->postmeta}.meta_value ASC, CASE WHEN (SELECT guid FROM {$wpdb->posts} WHERE ID = {$wpdb->postmeta}.meta_value) LIKE '%no2.png%' THEN 1 ELSE 0 END ASC, {$orderby} "; } return $orderby; }
How This Works
- Preserves Your Stock Sort: We keep your original
_stock_statussorting so in-stock products still appear first, followed by out-of-stock. - Adds Placeholder Image Check: The
CASEstatement in theposts_orderbyfilter checks if a product's featured image URL containsno2.png. Products with this placeholder get assigned a value of1, while others get0. Since we sort in ascending order,0values (non-placeholder) come before1values (placeholder). - Covers All Shop Pages: The function targets main shop pages, product categories, and tags to ensure consistent sorting across your store.
Notes
- Backup First: Always make a copy of
functions.phpbefore editing it, just in case something goes wrong. - No Thumbnail Products: If you have products without any featured image at all, we can tweak the
CASEstatement to push those to the end too—just let me know if you need that adjustment!
内容的提问来源于stack exchange,提问作者Guille Figueroa
相关产品推荐
相关产品推荐

