[英]Get WooCommerce product regular price and sale price from a WP_Query
我成功地在特定类别中运行大量折扣(假设类别 id 123 中的 -50%)并且在产品网格、产品页面和订单中一切运行顺利。 (Wordpress 5.7, Woocommerce: 5.1.0, 尝试了各种海量折扣插件)
但是问题是,当我尝试通过我制作的一个小插件在管理页面中打印列表时,我无法获得销售价格
我试过了:
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;
}
为什么没有销售价格? 我怎么才能得到它? 大多数产品都有变化。 产品页面包含销售运行的类别中所有产品的销售价格。
您需要查询“product”和“product_variation”帖子类型,在循环内不包括“variable”产品类型,如下所示:
$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;
}
它应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.