【问题标题】:How can I get Min and Max price of a woocommerce variable product in Custom loop?如何在自定义循环中获得 woocommerce 可变产品的最低和最高价格?
【发布时间】:2019-09-19 19:33:31
【问题描述】:

我在 Wordpress 中创建了一个自定义休息路线,它采用产品类别 ID 并将发送属于该类别的产品。

我的问题是我无法找到在我的自定义循环中获取可变产品最低和最高价格的方法。

谁能帮我解决这个问题? 谢谢

我尝试使用 get_variation_prices() 获取变体价格,但我似乎遗漏了一些东西。

add_action( 'rest_api_init' , 'wt_rest_api'); 
function wt_rest_api(){
   register_rest_route('wtrest','products',array(
           'methods'   => WP_REST_SERVER::READABLE,
           'callback'  => 'wtProductResults'
       )); 
} 

function wtProductResults($data){
    $products = new WP_Query([
           'post_type' => 'product',
           'tax_query' => array(
                               array(
                                   'taxonomy' => 'product_cat',
                                   'field' => 'term_id', //can be set to ID
                                   'terms' => $data['cat'] //if field is ID you can reference by cat/term number
                               )
                           )
        ]);

    $productsResults = [];
    global $woocommerce;
    global $product;
   $currency = get_woocommerce_currency_symbol();

    while($products->have_posts()){
        $products->the_post();
        $product_cat = get_term(  $data['cat'], 'product_cat', 'category', "OBJECT" );
        $regularPrice = get_post_meta( get_the_ID(), '_regular_price', true);
        $sale = get_post_meta( get_the_ID(), '_sale_price', true);
        $price = get_post_meta( get_the_ID(), '_price', true );
        array_push($productsResults , [
               'title' => get_the_title(),
               'productId' => get_the_id(),
               'permalink' => get_the_permalink(),
               'thumbnail' => get_the_post_thumbnail(),
               'excerpt' => get_the_excerpt(),
               'regularPrice' => $regularPrice,
               'price'     => $price,
               'salePrice' => $sale,
               'category' => $product_cat->name,
               'variationPrice' => get_variation_prices()//**Here is My problem**
            ]);
    }
    wp_reset_postdata();    
    return $productsResults;

}

这是我的代码,当我使用 get_variation_prices() 时,我的休息路线没有得到任何回应

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    函数get_variation_prices()WC_Product_Variable 类的方法,它专门用作可变产品实例对象的方法。它给出了一个包含所有变化价格的多维数组。

    要获得最小和最大变化价格,您必须使用WC_Product_Variable methods

    • get_variation_regular_price()get_variation_regular_price('max')
    • get_variation_sale_price()get_variation_sale_price('max')
    • get_variation_price()get_variation_price('max')

    现在在您的代码中:

    • 您首先需要获取WC_Product 实例对象。
    • 检查产品类型。
    • 删除 global $product;,因为它是空的且无用。
    • (您可能需要根据您的要求进行其他更改)

    现在有多种查询产品的方法:

    1) 使用WP_Query (就像你实际做的那样)

    function wtProductResults($data){
        global $woocommerce;
        
        $products = new WP_Query([
           'post_type' => 'product',
           'tax_query' => array( array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id', //can be set to ID
                'terms' => $data['cat'] //if field is ID you can reference by cat/term number
            ) )
        ]);
        
        $productsResults = [];
        $currency        = get_woocommerce_currency_symbol();
       
        if ( $products->have_posts() ) :
        while ( $products->have_posts() ) : $products->the_post();
        
        $product_cat = get_term(  $data['cat'], 'product_cat', 'category', "OBJECT" );
            
        // Get an instance of the WC_Product object
        $product = wc_get_product( get_the_ID() );
        
        if( $product->is_type('variable') ) {
            // Min variation price
            $regularPriceMin = $product->get_variation_regular_price(); // Min regular price
            $salePriceMin    = $product->get_variation_sale_price(); // Min sale price
            $priceMin        = $product->get_variation_price(); // Min price
        
            // Max variation price
            $regularPriceMax = $product->get_variation_regular_price('max'); // Max regular price
            $salePriceMax    = $product->get_variation_sale_price('max'); // Max sale price
            $priceMax        = $product->get_variation_price('max'); // Max price
        
            // Multi dimensional array of all variations prices 
            $variationsPrices = $product->get_variation_prices(); 
            
            $regularPrice = $salePrice = $price = '';
            $variationPrice = [
                'min' => $product->get_variation_price(),
                'max' => $product->get_variation_price('max')
            ];
        } 
        // Other product types
        else {
            $regularPrice   = $product->get_regular_price();
            $salePrice      = $product->get_sale_price();
            $price          = $product->get_price(); 
            $variationPrice = ['min' => '', 'max' => ''];
        }
        
        array_push( $productsResults , [
           'title'          => get_the_title(),
           'productId'      => get_the_id(),
           'permalink'      => get_the_permalink(),
           'thumbnail'      => get_the_post_thumbnail(),
           'excerpt'        => get_the_excerpt(),
           'regularPrice'   => $regularPrice,
           'price'          => $price,
           'salePrice'      => $salePrice,
           'category'       => $product_cat->name,
           'variationPrice' => $variationPrice,
        ]);
        
        endwhile; 
        wp_reset_postdata();
        endif;
        
        return $productsResults;
    }
    

    2) 使用 WC_Product_Query 代替:

    function wtProductResults($data){
        global $woocommerce;
        
        $products = wc_get_products( array(
            'status'    => 'publish',
            'limit'     => -1,
            'category'  => array($data['cat']),
        ) );
        
        $productsResults = [];
        $currency        = get_woocommerce_currency_symbol();
       
        if ( sizeof($products) > 0 ) :
        foreach ( $products as $product ) :
        
        $term_name = get_term( $data['cat'], 'product_cat' )->name;
        
        if( $product->is_type('variable') ) {
            // Min variation price
            $regularPriceMin = $product->get_variation_regular_price(); // Min regular price
            $salePriceMin    = $product->get_variation_sale_price(); // Min sale price
            $priceMin        = $product->get_variation_price(); // Min price
        
            // Max variation price
            $regularPriceMax = $product->get_variation_regular_price('max'); // Max regular price
            $salePriceMax    = $product->get_variation_sale_price('max'); // Max sale price
            $priceMax        = $product->get_variation_price('max'); // Max price
        
            // Multi dimensional array of all variations prices 
            $variationsPrices = $product->get_variation_prices(); 
            
            $regularPrice = $salePrice = $price = '';
            $variationPrice = [
                'min' => $product->get_variation_price(),
                'max' => $product->get_variation_price('max')
            ];
        } 
        // Other product types
        else {
            $regularPrice   = $product->get_regular_price();
            $salePrice      = $product->get_sale_price();
            $price          = $product->get_price(); 
            $variationPrice = ['min' => '', 'max' => ''];
        }
        
        array_push( $productsResults , [
           'title'          => $product->get_name(),
           'productId'      => $product->get_id(),
           'permalink'      => $product->get_permalink(),
           'thumbnail'      => $product->get_image(),
           'excerpt'        => $product->get_short_description(),
           'regularPrice'   => $regularPrice,
           'price'          => $price,
           'salePrice'      => $salePrice,
           'category'       => $term_name,
           'variationPrice' => $variationPrice,
        ]);
        
        endforeach; 
        endif;
        
        return $productsResults;
    }
    

    【讨论】:

    • 感谢您的回答。这是正确的方法我尝试了你说的第一种方法(WP_Query())并且效果很好,但我不知道为什么第二种方法(WC_Product_Query())对我不起作用。我还找到了一种方法,我想知道您对此的看法,我会将其作为此问题的另一个答案发送
    • @TaghiKhavari 我记得您在尝试使用get_variation_prices() 时在问题中询问了“最低”和“最高”可变价格以及您的相关问题......不可能猜到你正在寻找格式化的价格(您的问题中没有足够的上下文),现在我发现这对您来说是正确的选择。
    【解决方案2】:

    @LoicTheAztec 给出的答案非常好,我喜欢他编写代码的方式 但在我的情况下,我发现一个简单的改变完美地工作,我希望它是正常产品价格(如果是正常产品)和可变产品价格(如果是可变产品) 这是我所做的更改,我同时使用了 wc_get_product(get_the_id())get_price_html()

            $product = wc_get_product( get_the_id() );
            array_push($productsResults , [
                    'title'     => get_the_title(),
                    'productId' => get_the_id(),
                    'permalink' => get_the_permalink(),
                    'thumbnail' => get_the_post_thumbnail(),
                    'excerpt'   => get_the_excerpt(),
                    'category'  => get_the_terms(get_the_id(),'product_cat'),
                    'price'     => $product->get_price_html(),
            ]); 
    

    这段代码应该在我与WP_Query()一起使用的while循环中

    【讨论】:

    • $product->get_price_html() 正是我想要的!不错!
    【解决方案3】:
    add_filter( 'woocommerce_variable_price_html', 'bbloomer_variation_price_format_min', 9999, 2 );
    
    function bbloomer_variation_price_format_min( $price, $product ) {
       $prices = $product->get_variation_prices('min', true );
       $maxprices = $product->get_variation_price( 'max', true ) ;
       $min_price = current( $prices['price'] );
       //$max_price = current( $maxprices['price'] );
       $minPrice = sprintf( __( 'from: %1$s', 'woocommerce' ), wc_price( $min_price ) );
       $maxPrice = sprintf( __( 'to: %1$s', 'woocommerce' ), wc_price( $maxprices ) );
       return $minPrice .' ' .$maxPrice ;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2020-10-29
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多