These 2 code snippets exclude on Sale products from the shop page loop in WooCommerce.
The following gallery images show on sale products included in the shop page loop on the left and excluded on the right.
Add one of the PHP snippets to the end of your child themes functions file or custom functionality/code snippets plugin.
How The Code Works
Hook Registration :
add_actionfunction is used to register an action hook. The action hook is
pre_get_posts, indicating that the attached function will be executed before the main query is executed.
Function Declaration :
- The function
wc_exclude_sale_items_from_shop_pageis defined to handle the logic associated with excluding sale items from the shop page.
Conditional Check :
- The function begins with a conditional check using
if. It checks whether the current request is in the admin area (
is_admin()) or if it’s not the main query (
! $query->is_main_query()). If either condition is true, the function returns, indicating that no further action should be taken.
Main Shop Page Check :
- Within the conditional block, there’s a check using
is_shop(). This checks if the current page is the main shop page. If true, the logic inside the block is executed.
Modify Query :
$query->set()method is used to modify the query parameters. Specifically, it sets the
meta_queryparameter to an array with a single array element.
- Within the
meta_queryarray, there’s an array with two elements:
compare. This is specifying a meta query that looks for products where the
_sale_pricemeta key does not exist (
'compare' => 'NOT EXISTS').
- In summary, this code is a WordPress action that hooks into the
pre_get_postsevent. When triggered, it modifies the main query before it is executed. The modification aims to exclude both simple and variable products with a sale price from the main shop page by checking for the existence of the