如何在自定义循环中获取 woocommerce 可变产品的最低和最高价格?

2023-11-29

我在 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()我没有从休息路线收到任何回复


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

获取最小和最大变化价格,你必须使用WC_Product_Variable methods:

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

现在在您的代码中:

  • 你首先需要得到WC_Product实例对象。
  • 检查产品类型。
  • remove 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在自定义循环中获取 woocommerce 可变产品的最低和最高价格? 的相关文章

  • PDO 连接字符串:最好的方法是什么? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我想使用 php pdo 制作一个后端应用程序 我发现了很多不同的方法来处理 PDO 连接字符串 我想知道使用 pdo 执行连接字符串的最佳方法
  • PHP Imagick - setTextEncoding() 函数不起作用

    我正在尝试在 Imagick 对象上添加一些文本 但是我使用 setTextEncoding 函数 它仍然不起作用 draw new ImagickDraw draw gt setTextEncoding utf 8 draw gt set
  • 使用 google 检查 url,安全 = 活动

    如何检查 url 是否被 google 显示 Example https www google com search q redtubex xxx safe active Code input http www example com in
  • PHP runkit_function_rename 不起作用?

    这段代码不起作用 为什么不 我真正想要的是这个 我正在使用一个具有功能的系统 当我在本地主机上时 我希望该函数做一些不同的事情 我想用自己的东西覆盖该函数 也欢迎所有替代方案 您是否安装了 PECL 扩展 http www php net
  • 未找到“Twilio\Rest\Client”类

    我正在尝试使用 twilio php api 这是我的代码
  • 升级到 Yosemite 后 Apache 配置损坏

    昨天我升级到 Yosemite 现在我的 Web 开发本地配置不再起作用 我设法在下面设置了一个 userdir Users user public html我可以通过以下方式访问所有网站localhost user websitename
  • 在 Magento 中使用缩略图切换基本图像

    在定制的产品视图页面上 我正在处理基本图像 大图像 和缩略图列表 这些缩略图是与媒体库中的产品相关的其他图像 它们只是普通图像 而不是定义的图像 缩略图 我的任务是获取它 以便当您单击缩略图时它会更改上面的基本图像 我已经可以工作了 但是我
  • 什么是 no-debug-non-zts-20090626?

    In php ini I have extension dir usr lib php extensions 然而 运行php config gives extension dir usr lib php extensions no deb
  • 循环遍历数据数组并打印“递增”字母

    我需要循环遍历数据数组并为每个数组值打印一个 递增 字母 我知道我可以这样做 array array 11 33 44 98 1 3 2 9 66 21 45 array to loop through letters array a b
  • Yii2 - 如何自动加载自定义类?

    我创建了以下自定义类 我想在我的 Yii2 应用程序中使用它 common components helper CustomDateTime php namespace common components helper class Cust
  • Yii 框架将变量从控制器传递到视图

    要将变量传递给登录视图 我使用 this gt render login array model gt model 但我还需要在模板部分 footer php 中访问此变量 我试试这个 this gt render footer array
  • 如何在 Centos 7 上手动安装 PHP-Zts

    我想安装 pthreads 当我尝试安装时 我会收到此错误 checking for ZTS no configure error pthreads requires ZTS please re compile PHP with ZTS e
  • XML 和 INI 哪个更快?

    我想知道 XML 是否比 INI 更快 反之亦然 我正在开发一个包含许多文件的网站 这个问题与我的问题有关关于包含许多文件 https stackoverflow com questions 7777522 too many include
  • 获取本周星期一和星期五的日期 (PHP)

    如何获取本周周一和周五的日期 我有以下代码 但如果当天是星期日或星期六 则会失败 current day date N days to friday 5 current day days from monday current day 1
  • PHP 读取 XML 播客 RSS 源

    好的 我正在为朋友的播客网站创建一个页面 列出他的播客的所有剧集 本质上 我所寻找的只是如何阅读 RSS 提要 解析出节点 并将信息显示在屏幕上 最终 我将创建一个可以播放剧集的播放器 但那是很久以后的事了 这就是我阅读 RSS 源的方式
  • bash.sh 运行 cron 的权限被拒绝

    如何在这里使用 bash 脚本运行 cron 我做了如下操作 这里有错误 我想知道如何在 ubuntu 中做到这一点 我现在对它感到震惊 bash sh 文件 bin bash cd var www Controller usr bin p
  • 如何在 PHP 中去除字符串中的所有空格? [复制]

    这个问题在这里已经有答案了 我怎么能够strip remove all spaces of a string in PHP 我有一个string like string this is my string 输出应该是 thisismystr
  • 开发中的 Laravel 和视图缓存——无法立即看到变化

    我和一些朋友决定开始一个项目 我们偶然发现了 Laravel 并认为它可能是一个很好的工具 我们开始在本地使用它来开发一些页面 并注意到一些奇怪的事情 当我们用不同的信息更新视图时 大约需要 5 到 10 分钟视图信息才会发生变化 这就像
  • 如何用破折号替换所有大写字母,用正则表达式替换所有小写字母?

    如何在 php 中用破折号和小写字母替换所有大写字母 Such as understandRegexBetter to understand regex better 我的 Google fu 和对以下代码的实验并没有让我走得太远 echo
  • 如何找到数组中的最小数字并返回该数组的主索引?

    我有一个如下所示的数组 我想找到 diff 索引中数字最小的数组 所以在这种情况下 我想取回数组 7 我需要的只是数组编号 即 7 而不是任何其他信息 我知道我可以使用 array column 轻松找到最小的数字 但如何返回整个数组索引

随机推荐