簡體   English   中英

從 WP_Query 獲取 WooCommerce 產品正常價格和銷售價格

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM