从 WP_Query 获取 WooCommerce 产品的正常价格和销售价格

时间:2021-03-28 17:44:58

标签: php wordpress woocommerce backend discount

我成功地在特定类别中进行了大规模折扣(假设类别 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;
}

为什么没有促销价?我怎么才能得到它?大多数产品都有变化。产品页面包含销售运行的类别中所有产品的销售价格。

1 个答案:

答案 0 :(得分:1)

您需要查询“product”和“product_variation” post type 排除,在循环内,“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;
}

它应该可以解决您的问题。