使用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个对象。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...