I have discounted products by 30%, 40%, and 50%. Now I need to create an archive template that would filter out only products discounted by 30% and link to it directly from Product Category list.
All of this should look like archive-product.php
so I can create a new template archive-product-sale.php
for the new page displaying that discount.
I was trying to modify archive-product.php
by adding
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'OR',
array( // Simple products type
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array( // Variable products type
'key' => '_min_variation_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
query_posts( $args );
just above <?php if ( ( function_exists( 'woocommerce_product_loop' ) && woocommerce_product_loop() ) || have_posts() ) : ?>
but found out that nothing is being returned. This was supposed to be my first step towards the solution, just to list on-sale products, then to figure out how to filter only the ones discounted by 30%.
I'm completely stuck at the moment with no solution in my mind.
How do I get only specific discounted products to be displayed on a page?
My Answer:
'product',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array(
'key' => '_sale_price',
'value' => 0,
'compare' => '<',
'type' => 'numeric'
),
array(
'key' => '_sale_price',
'value' => 30,
'compare' => '>=',
'type' => 'numeric'
)
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
wc_get_template_part( 'content', 'product' );
}
}
wp_reset_postdata();
This code will filter out only products that have a sale price greater than 0 and less than 30, effectively showing only products discounted by 30%. You can then create a new template file called archive-product-sale.php and link to it from your Product Category list.
Rate this post
3 of 5 based on 7523 votesComments