gpt4 book ai didi

wordpress - WC_Product_Query 不适用于 have_posts()

转载 作者:行者123 更新时间:2023-12-04 14:38:06 29 4
gpt4 key购买 nike

我正在尝试像使用自定义帖子类型一样遍历我的 WooCommerce 产品。但由于某种原因,这种方法不起作用。我在使用 have_posts() 时遇到与我有关的错误.我究竟做错了什么?

错误

Uncaught Error: Call to a member function have_posts() on array



我的代码
<?php
$query = new WC_Product_Query( array(
'limit' => 10,
'orderby' => 'date',
'order' => 'DESC'
) );

$products = $query->get_products();

if( $products->have_posts() ) {
while( $products->have_posts() ) {
$products->the_post();
echo the_permalink();
}
} ?>

更新

我发现使用 foreach 循环确实像下面这样工作;
<?php
foreach( $products as $product ) {
echo $product->get_title();
} ?>

但我仍然想了解为什么这种方法不适用于 have_posts()

最佳答案

$query = new WC_Product_Query(array(
'limit' => 10,
'orderby' => 'date',
'order' => 'DESC'
));

$products = $query->get_products();

if (!empty($products)) {
foreach ($products as $product) {

echo get_permalink($product->get_id());
}
}

功能 have_post()是WordPress的成员函数 WP_Query类 - 和 WooCommerce WC_Product_Query类(class)正在扩展 WC_Object_Query类,而不是 WP_Query - 所以这个函数不能被调用

关于wordpress - WC_Product_Query 不适用于 have_posts(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54853854/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com