Как получить минимальную и максимальную цену на переменный продукт woocommerce в пользовательском цикле? - PullRequest
1 голос
/ 01 мая 2019

Я создаю собственный маршрут отдыха в WordPress, который принимает идентификатор категории продукта и отправляет продукты, относящиеся к этой категории. Моя проблема в том, что я не могу найти способ получения минимальных и максимальных цен на переменный продукт в моем пользовательском цикле , Кто-нибудь может мне помочь с этим вопросом? Спасибо

Я пытался получить цену изменения, используя 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(), я не получил никакого ответа от моего маршрута отдыха

Ответы [ 2 ]

0 голосов
/ 02 мая 2019

Ответ, который дал @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(),
        ]); 

этот код должен быть внутри цикла while, который я использовал с WP_Query()

0 голосов
/ 01 мая 2019

Функция get_variation_prices() является методом класса WC_Product_Variable и работает исключительно как метод для объекта экземпляра переменного продукта.Он дает многомерный массив всех цен вариантов.

Чтобы получить минимальные и максимальные цены вариантов , необходимо использовать WC_Product_Variable методы :

  • 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...