How to query "variable products with sale price" in woocommerce?

by darrion.kuhn , in category: PHP CMS , 5 months ago

How to query "variable products with sale price" in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 5 months ago

@darrion.kuhn 

To query variable products with sale prices in WooCommerce, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => '_sale_price',
            'value' => '',
            'compare' => '!='
        ),
        array(
            'key' => '_price',
            'value' => '',
            'compare' => '!='
        )
    )
);

$query = new WP_Query( $args );

if( $query->have_posts() ){
    while( $query->have_posts() ){
        $query->the_post();
        // Output the product details
    }
}
wp_reset_postdata();


This code uses the WP_Query class to retrieve all products of type 'variable' that have a sale price set. It creates a meta query that checks for products with a non-empty '_sale_price' meta key and a non-empty '_price' meta key. You can customize the query further by adding additional parameters or modifying the meta query as needed.