dsc6517 2018-10-08 16:31
浏览 272
已采纳

使用Woocommerce中的wc_get_products查询所有没有API的产品

In Woocommerce I am trying to get all products using wc_get_products() as follow:

$args = array( 'status' => 'publish' );
$products = wc_get_products( $args );
return $products;

But it return an empty string.

How can I get all products using wc_get_products()? What I am doing wrong?

  • 写回答

2条回答 默认 最新

  • douyao2529 2018-10-08 21:03
    关注

    Your code works and will give you an array of the 10 last created WC_Product objects. So when you return this array of WC_Product objects, it gives nothing as it's not a string.

    If you want to get all products you need to add 'limit' argument with a value of -1 like:

    // An array of all published WC_Product Objects
    $products = wc_get_products( array( 'status' => 'publish', 'limit' => -1 ) );
    
    // Displaying the number of products in this array
    echo '<p>Number of products: ' . sizeof( $products ) . '</p>';
    
    // Loop through products and display some data using WC_Product methods
    foreach ( $products as $product ){
        echo '<p>';
        echo 'Type: '  . $product->get_type() . '<br>';  // Product type
        echo 'ID: '    . $product->get_id() . '<br>';    // Product ID
        echo 'Title: ' . $product->get_title() . '<br>'; // Product title
        echo 'Price: ' . $product->get_price();          // Product price
        echo '</p>';
    }
    

    Example - The following code will output in a string a coma separated suite of all your product IDs:

    echo '<p>Products IDs list: ' . implode( ', ', wc_get_products( array( 'status' => 'publish', 'limit' => -1, 'return' => 'ids' ) ) ) . '</p>';
    

    Tested and works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助