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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器