admin管理员组文章数量:1427301
I am trying to list my products using WP_Query
.
I have used a query such as the following one:
$slider_products_q = new WP_Query([
'posts_per_page' => 8,
'post__in' => $slides_product_ids,
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC'
]);
It works perfectly, however when I want to access WooCommerce methods inside the loop such as get_html_price
it becomes a bit tricky.
I have managed to handled it using this way, yet the performace is not good and the query takes about '0.7' seconds to load up.
This is how I loop though each item:
if ($slider_products_q->have_posts()):
while($slider_products_q->have_posts()):
$slider_products_q->the_post();
$product_id = get_the_ID();
global $product;
...
Then I could call $product->get_price_html();
method.
I also did try to query products using Woocommerce methods but since they load up a lot of custom attributes the query takes even much more time.
Any suggestion of how to improve this?
By the way I only care about using Woocommerce methods such as get_price_html
.
Attributes or custom terms are not necessary at all.
I am trying to list my products using WP_Query
.
I have used a query such as the following one:
$slider_products_q = new WP_Query([
'posts_per_page' => 8,
'post__in' => $slides_product_ids,
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC'
]);
It works perfectly, however when I want to access WooCommerce methods inside the loop such as get_html_price
it becomes a bit tricky.
I have managed to handled it using this way, yet the performace is not good and the query takes about '0.7' seconds to load up.
This is how I loop though each item:
if ($slider_products_q->have_posts()):
while($slider_products_q->have_posts()):
$slider_products_q->the_post();
$product_id = get_the_ID();
global $product;
...
Then I could call $product->get_price_html();
method.
I also did try to query products using Woocommerce methods but since they load up a lot of custom attributes the query takes even much more time.
Any suggestion of how to improve this?
By the way I only care about using Woocommerce methods such as get_price_html
.
Attributes or custom terms are not necessary at all.
1 Answer
Reset to default 2The global $product;
doesn't work in a custom WP_Query
, instead use wc_get_product()
like:
if ($slider_products_q->have_posts()):
while($slider_products_q->have_posts()):
$slider_products_q->the_post();
$product_id = get_the_ID();
$product = wc_get_product($product_id);
$price_html = $product->get_price_html()
// ...
Now you can use any WC_Product
methods on $product
variable.
Alternatively, you could use a WC_Product_query
.
本文标签: wp queryHow to get the WCProduct Object when using a WPQuery in WooCommerce
版权声明:本文标题:wp query - How to get the WC_Product Object when using a WP_Query in WooCommerce 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745494711a2660756.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论