在 WooCommerce 中使用 WC_Query 按作者 ID 获取产品?

我尝试使用 WooCommerce 中的 WC_Query 通过帖子作者 id 获取产品,因此我尝试包含一个新的自定义元密钥 "_author",其中包含以下内容:


add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handling_custom_meta_query_keys', 10, 3 );

function handling_custom_meta_query_keys( $wp_query_args, $query_vars ) {

    $meta_key = '_author'; 

    if ( ! empty( $query_vars[$meta_key] ) ) {

        $wp_query_args['meta_query'][] = array(

            'key'     => $meta_key,

            'value'   => esc_attr( $query_vars[$meta_key] ),

            'operator' => '==', 

        );

    }

    return $wp_query_args;

}

然后我尝试将它与以下内容一起使用wc_get_products():


$product_list = wc_get_products( array('_author' => get_current_user_id()) );

但它返回空数组。任何想法?


繁花不似锦
浏览 115回答 2
2回答

富国沪深

您可以使用未记录的参数“author”在 WC_Query 中简单地按作者 ID 获取产品,如下所示:$products = wc_get_products( array(    'status'    => 'publish',    'limit'     => -1,    'author'    => get_current_user_id()) );你将得到一个WC_Product对象数组

FFIVE

您可以像这样使用自定义查询<?php$authorID = get_the_author_meta('ID');$args = array(&nbsp; &nbsp; 'post_type' => 'product',&nbsp; &nbsp; 'post_status' => 'publish'&nbsp; &nbsp; 'posts_per_page' => 12,&nbsp; &nbsp; 'product_cat' => 'pants'&nbsp; &nbsp; 'author'&nbsp; &nbsp; => $authorID);$loop = new WP_Query( $args );?>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<div class="author_products">&nbsp; &nbsp; <?php if ( $loop->have_posts() ) { ?>&nbsp; &nbsp; &nbsp; &nbsp; <ul class="author_pubproducts">&nbsp; &nbsp; &nbsp; &nbsp; <?php while ( $loop->have_posts() ) : $loop->the_post();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; woocommerce_get_template_part( 'content', 'product' );&nbsp; &nbsp; &nbsp; &nbsp; endwhile; ?>&nbsp; &nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; &nbsp; &nbsp; <?php&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo __( 'No products found', 'textdomain' );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; wp_reset_postdata();&nbsp; &nbsp; ?>希望能成功
打开App,查看更多内容
随时随地看视频慕课网APP