Skip to content

Instantly share code, notes, and snippets.

@amirhp-com
Last active December 2, 2024 05:31
Show Gist options
  • Save amirhp-com/5b260bcff5b9b094295d293054cef951 to your computer and use it in GitHub Desktop.
Save amirhp-com/5b260bcff5b9b094295d293054cef951 to your computer and use it in GitHub Desktop.
WooCommerce: Display In-Stock Products First
<?php
/**
* WooCommerce: Display In-Stock Products First
* https://www.linkedin.com/posts/activity-7254955257355456515-ypfV
*
* This code snippet reorders products in WooCommerce to show
* in-stock items first, followed by out-of-stock items. It uses
* the 'posts_clauses' filter to modify the default product query.
*
* Usage:
* - Add the code to your theme's 'functions.php' file or create
* a custom plugin to implement it.
* - The code checks if the query is on a product archive page and
* modifies the query to prioritize in-stock products, ensuring
* better visibility for customers.
*
* Developed by: amirhp-com
* Website: https://amirhp.com
*
* Disclaimer:
* - Use this code at your own risk. The developer is not responsible
* for any issues, errors, or malfunctions that may occur as a result
* of using this code. Always test in a development environment first.
*/
add_filter("posts_clauses", "reorder_products_in_stock_first", 10, 2);
function reorder_products_in_stock_first($clauses, $query) {
if (is_admin() || !$query->is_main_query() || !$query->is_post_type_archive('product') && !$query->is_tax('product_cat') ) {return $clauses;}
global $wpdb;
$clauses['join'] .= " LEFT JOIN {$wpdb->postmeta} AS pm_stock ON {$wpdb->posts}.ID = pm_stock.post_id AND pm_stock.meta_key = '_stock_status' ";
$clauses['orderby'] = " pm_stock.meta_value ASC, " . $clauses['orderby'];
return $clauses;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment