Sort WooCommerce products by the highest discount using JetSmartFilters
Thu Jan 23 2025 19:35:44 GMT+0000 (Coordinated Universal Time)
Saved by @Y@sir
To sort your WooCommerce products by the highest discount using JetSmartFilters' **Sort Filter**, you can use the following steps and PHP snippet: --- ### **1. Add a Custom Meta Key for Discount Calculation** You need to calculate and store the discount as a custom meta key for each product. This meta key will be used in the JetSmartFilters Sort Filter. Add the following PHP snippet to your theme's `functions.php` file or a custom plugin: ```php add_action('save_post_product', 'update_product_discount_meta'); function update_product_discount_meta($post_id) { // Ensure it's a product post type if (get_post_type($post_id) !== 'product') { return; } // Get the product object $product = wc_get_product($post_id); if (!$product) { return; } // Get the regular and sale prices $regular_price = (float) $product->get_regular_price(); $sale_price = (float) $product->get_sale_price(); // Calculate the discount percentage if ($regular_price > 0 && $sale_price > 0) { $discount = round((($regular_price - $sale_price) / $regular_price) * 100); } else { $discount = 0; // No discount } // Update the custom field with the discount value update_post_meta($post_id, '_product_discount', $discount); } ``` --- ### **2. Recalculate Discounts for Existing Products** To apply the discount calculation to existing products, you can run a script or use a plugin like **WP Crontrol** to loop through all products and update their discounts. ```php add_action('init', 'recalculate_discounts_for_all_products'); function recalculate_discounts_for_all_products() { $args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'fields' => 'ids', ); $products = get_posts($args); foreach ($products as $product_id) { update_product_discount_meta($product_id); } } ``` This will process all products and save their discounts. After running it once, you can remove or comment out this action. --- ### **3. Configure the JetSmartFilters Sort Filter** In the **Sort Filter** settings (as shown in your screenshot): 1. **Order By**: Select **Meta Key Numeric** (since the discount is a number). 2. **Key**: Enter `_product_discount` (the meta key used in the PHP snippet). 3. **Order**: Set to **DESC** (to sort from highest to lowest discount). --- ### **4. Test the Sorting** - Add the JetSmartFilters **Sort Filter** to the page where your product listing grid is displayed. - Ensure the sorting works as expected, with the products having the highest discount appearing first.
Comments