如何在自定义循环中获取 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 可变产品的最低和最高价格? 的相关文章

  • 让我的函数访问外部变量

    我外面有一个数组 myArr array 我想让我的函数访问其外部的数组 以便它可以向其中添加值 function someFuntion myVal some processing here to determine value of m
  • MySQL:计算日期/时间之间的差异 - 仅在周一至周五“工作周”期间

    我需要计算开始日期 时间和结束日期 时间之间的差异 但是 我只想在 5 天的工作周内执行此操作 不包括周六 周日 做这个的最好方式是什么 我的想法是 从日期开始 我必须获取星期几 如果是工作日 那么我将添加到累加器中 如果不是 那么我不会添
  • 有没有一个 PHP 函数可以交换两个变量的值?

    比如说我有 var1 ABC var2 123 在某些条件下我想像这样交换两者 var1 123 var2 ABC 是否有一个 PHP 函数可以执行此操作 而不必创建第三个变量来保存其中一个值 然后重新定义每个值 就像这样 var3 var
  • Facebook 错误“验证验证码时出错”

    非常奇怪的错误 我用基德http developers facebook com docs authentication http developers facebook com docs authentication 所以我创建了对fb的
  • 如何从 WooCommerce 中的订单获取客户详细信息?

    我有一个函数可以执行此操作 order new WC Order order id customer new WC Customer order id 我如何从中获取客户详细信息 我已经尝试了文档中的所有内容 但不知何故 只存在一些细节 但
  • Laravel 保存文件将其发布为 bin 文件

    我试图在 laravel 中保存文件 但它最终被保存为 bin 文件 file request gt file file name Carbon now gt format Y m d strtotime Carbon now file g
  • 帮我用 PHP 解析这个文件

    Fri Nov 27 10 00 01 EST 2009 974 12506 Fri Nov 27 11 00 01 EST 2009 988 12655 Fri Nov 27 12 00 01 EST 2009 1005 12886 Fr
  • 命令“tinker”未定义

    从 5 3 升级到 5 4 后 请按照说明操作 为了继续使用 Tinker Artisan 命令 您还应该安装 laravel tinker 软件包 composer require laravel tinker 安装软件包后 您应该添加
  • php 无法连接到 mysql,错误为 13(但命令行可以)

    我在新安装的服务器中遇到了奇怪的情况 谷歌这次似乎无法帮助我 我无法从我的 php 代码连接到 远程 mysql 当我尝试从同一服务器上的命令行连接时 连接成功 无法连接 无法连接到 MYSQL SERVER 上的 MySQL 服务器 13
  • 字符串替换多个值

    我有一个看起来像这样的字符串 布拉布拉 亚达亚达 布拉布拉 亚达亚达 有没有办法只替换前两个 或最后两个 以便我可以获得下一个输出 Bla bla a href link1 yada yada a bla bla yada yada 如有必
  • 如何在 MAMP 上显示错误?

    我有 MAMP 但我不知道如何在其上显示错误 当我的 php 代码出现错误时 它只显示空白页 我在 Google 上搜索过 我发现我必须在所有文件夹和版本上将其更改为 display errors on 并将其包含在我的页面上 错误报告 E
  • 如何从谷歌地图中的纬度和经度获取地址位置? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 所以我有纬度和经度就像44 4647452 and 7 3553838 我需要获得如下地址 米兰 意大利 str 肯尼迪 89 我怎样才能
  • 无法创建可锁定文件 - Laravel 8 和 PHP 8

    我被困在 Laravel 项目中 我已经使用 Laravel 很多年了 但从未发生过这种情况 我正在使用 Vagrant 一如既往 并且只在 PHP 8 中发生这种情况 使用 php 7 X 的其他项目不会发生这种情况 USER 和 GRO
  • Python 结构的 PHP 替代品

    我很高兴在我的 Python 项目中使用 Fabric 进行部署 现在我正在从事一个更大的 PHP 项目 想知道是否有类似 PHP 的 Fabric 之类的东西 唔 为什么这有关系 Fabric 只是 python 脚本 所以它与项目语言无
  • Preg_match PHP 到 java 的翻译

    我在将 php preg match 转换为 java 时遇到一些问题 我以为我的一切都是正确的 但它似乎不起作用 这是代码 原始PHP Pattern for 44 Character UUID pattern 0 9A F 44 if
  • CakePHP 与 Bootstrap(来自 Twitter)

    我是 CakePHP 的新手 我想知道一种在与蛋糕结合的布局中使用 Twitter 的 Bootstrap 的方法 我主要关心的是让 Form Helper 继续正常运行 因为我认为它使用预先配置的 CSS 类 如果我更改默认的 css 我
  • PHP 根据需要添加额外的空格

    考虑以下代码 div div search php and category php本质上是相同的结构 具有一些特定内容的 div 容器 这里没什么特别的 纯 HTML div class component div 但是 当插入时requ
  • PHP 中二进制的前缀是什么?

    两者都不是0x nor 0 它是什么 有没有 从 PHP 5 4 开始 二进制数的前缀是 0b For ealier version there is no such prefix Instead you can use 0x for he
  • WordPress:wpdb->插入与wpdb->准备(wpdb->查询(“INSERT

    我想知道 WordPress 的插入功能是否也向数据添加斜杠 如果没有 准备查询方法似乎可以更好地防止 SQL 注入 我尝试在 codex api 中查找问题 然而 它似乎没有记录 谢谢 这个问题有点老了 自从提出这个问题以来 法典可能已经
  • slim 3 php 应用程序无法在 CentOS 上运行 nginx 访问被拒绝可能是由于 session_start() 函数

    我最近一直在努力在 macOS 上的 virtualbox 上的 CentOS 7 上安装最新的 nginx 1 14 php 7 2 5 和 mariaDB 10 3 7 php终于可以工作了 我已经测试过了php info index

随机推荐