WooCommerce Exclude On Sale Products from Shop Page

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.

Installation

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 :

  • The add_action function 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_page is 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 :

  • The $query->set() method is used to modify the query parameters. Specifically, it sets the meta_query parameter to an array with a single array element.
  • Within the meta_query array, there’s an array with two elements: key and compare. This is specifying a meta query that looks for products where the _sale_price meta key does not exist ('compare' => 'NOT EXISTS').

Conclusion :

  • In summary, this code is a WordPress action that hooks into the pre_get_posts event. 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 _sale_price meta key.

Related Products

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.