如何解决使用WP查询遍历WooCommerce产品的元价值
我正在使用WooCommerce API,我想创建一个列出我特定产品的新端点。我们以前使用插件创建了新字段,我想检查一下。如果该属性在设置中被选中,则显示它,否则不显示。
产品的新属性(高级设置中的复选框):
woocommerce_wp_checkbox(
array(
'id' => '_checkbox_badge_hot','desc' => __('set the checkbox','woocommerce'),'label' => __('Hot','desc_tip' => 'true','value' => get_post_meta( $post->ID,'_checkbox_badge_hot',true )
)
);
应该列出我产品的代码(现在,如果我尝试向端点请求,它将不断加载):
function get_hot_products(){
$args_for_hot_product = array(
'post_type' => 'product','posts_per_page' => -1
);
$loop = new WP_Query( $args_for_hot_product );
$hotproducts = [];
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content','product' );
endwhile;
while ( $loop->have_posts() ): $loop->the_post(){
$hot = $loop->get_meta('_checkbox_badge_hot');
if( $hot === "yes" ){
array_push($hotproducts,$hot);
}
}
//wp_reset_postdata();
return $hotproducts;
}
add_action( 'rest_api_init',function () {
register_rest_route( '/wc/v3','/featuredproducts',array(
'methods' => 'GET','callback' => 'get_hot_products',) );
} );
感谢您的帮助!
解决方法
要使用WP_Query
获取并显示具有特定自定义字段值的所有产品,只需使用eta查询,如下所示:
function display_hot_products(){
$loop = new WP_Query( array(
'post_type' => 'product','post_status' => 'publish','posts_per_page' => -1,'meta_query' => array( array(
'key' => '_checkbox_badge_hot','value' => 'yes','compare' => '=',)),));
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
the_title(); // Display product title
endwhile;
wp_reset_postdata();
endif;
}
请不要忘记,使用WP_Query
对象时,您会得到WC_Post
个对象,而不是WC_Product
个对象。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。