For all #woocommerce users, please share you approach to create the sale products. This sales page should work and look like shop page. For example: the sales page should have pagination, products sorting etc.
Here’s how to implement it:
Step 1: Add the Rewrite Rule
add_action('init', 'gs_add_sale_rewrite_rule');
function gs_add_sale_rewrite_rule() {
add_rewrite_rule(
'^shop/sale/?$', // Custom URL
'index.php?post_type=product&sale_products=1', // Query vars
'top'
);
}
Step 2: Add the Query Variable
add_filter('query_vars', 'gs_add_sale_query_var');
function gs_add_sale_query_var($vars) {
$vars[] = 'sale_products';
return $vars;
}
Step 3: Filter the main query to display only sale products when the sale_products variable is set.
add_action('pre_get_posts', 'filter_sale_products_query');
function filter_sale_products_query($query) {
if (!is_admin() && $query->is_main_query() && get_query_var('sale_products')) {
$query->set('post_type', 'product');
$query->set('meta_query', array(
array(
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'NUMERIC'
)
));
}
}
The above code is working fine. But, it gives 404 error when I am opened the /page/2 from pagination.
I found the solution. I replaced step-1 and step-3 with the following code.
Step 1: Add the Rewrite Rule
add_action('init', 'add_sale_rewrite_rule');
function add_sale_rewrite_rule() {
add_rewrite_rule(
'^sale/?$',
'index.php?post_type=product&sale_products=1&paged=1',
'top'
);
// Rule for subsequent pages
add_rewrite_rule(
'^sale/page/([0-9]{1,})/?$',
'index.php?post_type=product&sale_products=1&paged=$matches[1]',
'top'
);
}
Step 2: Add the Query Variable
add_filter('query_vars', 'gs_add_sale_query_var');
function gs_add_sale_query_var($vars) {
$vars[] = 'sale_products';
return $vars;
}
Step 3: Filter the main query to display only sale products when the sale_products variable is set.
add_action('pre_get_posts', 'filter_sale_products_query');
function filter_sale_products_query($query) {
if (!is_admin() && $query->is_main_query() && get_query_var('sale_products')) {
$query->set('post_type', 'product');
$query->set('meta_query', array(
array(
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'NUMERIC'
)
));
// Handle pagination
$paged = get_query_var('paged') ? absint(get_query_var('paged')) : 1;
$query->set('paged', $paged);
// Set posts per page
//$query->set('posts_per_page', 12); // Adjust as needed
}
}
Step 4: Flush Rewrite Rules
After adding this code, you must flush rewrite rules. You can do this by visiting Settings > Permalinks in the WordPress admin area and clicking “Save Changes.”
Add the code in the child theme’s functions.php
Code tested and worked