Reputation: 77
I run mass discounts in a specific category successfully (lets say -50% in category id 123) and everything runs smoothly in product grid, product page and orders. (Wordpress 5.7, Woocommerce: 5.1.0, tried various mass-discount plugins)
However the problem is that when I try to print a list in an admin page through a small plugin I made, I can not get the sale price
I tried:
global $woocommerce;
$args = array('post_type'=>'product','post_status'=>'publish','ignore_sticky_posts'=>1);
$query = new WP_Query( $args );
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post();
global $product;
$product = wc_get_product( get_the_ID() );
echo $product->get_sale_price()."<br>"; //prints empty
echo $product->get_price()."<br>"; //prints the initial price
echo wc_price( wc_get_price_including_tax( $product ) ).'<br>'; //prints the initial price
echo $product->get_variation_sale_price( 'min', true ).'<br>'; //prints the initial price
if ( $product->is_on_sale() ){
echo 'is on sale<br>'; //it never prints so it does not recognise the product as in sale
}
endwhile;
}
Why is there no sale price? How can I get it? Most products have variations. The product page has the sale price in all products in the category that the sale runs.
Upvotes: 3
Views: 4760
Reputation: 253784
You need to query "product" and "product_variation" post type excluding, inside the loop, "variable" product type as follows:
$query = new WP_Query( array(
'post_type' => array('product', 'product_variation'),
'post_status' => 'publish',
'posts_per_page' => -1,
'ignore_sticky_posts' => 1,
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post();
$product = wc_get_product( get_the_ID() );
if ( ! $product->is_type('variable') ){
$active_price = $product->get_price();
$regular_price = $product->get_regular_price();
echo 'Product Id: ' . $product->get_id() . ' <em>(type: ' . $product->get_type() . ')<em><br>';
if ( $product->is_on_sale() {
echo 'Sale price: ' . $active_price . ' <em>(regular price: ' . $regular_price . ')<em><br>';
} else {
echo 'Price: '. $active_price .'<br>';
}
}
endwhile;
}
It should solve your issue.
Upvotes: 2