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

问题描述

我试图在WooCommerce中使用WC_Query通过帖子作者ID获得产品,因此我尝试在新的自定义meta_key“ _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()) );

,但它返回空数组。有想法吗?

解决方法

您可以使用未记录的参数“ author'”简单地通过WC_Query中的作者ID获得产品:

$products = wc_get_products( array(
    'status'    => 'publish','limit'     => -1,'author'    => get_current_user_id()
) );

您将获得WC_Product个对象的数组

,

您可以像这样使用自定义查询

<?php

$authorID = get_the_author_meta('ID');

$args = array(
    'post_type' => 'product','post_status' => 'publish'
    'posts_per_page' => 12,'product_cat' => 'pants'
    'author'    => $authorID
);

$loop = new WP_Query( $args );

?>        
<div class="author_products">
    <?php if ( $loop->have_posts() ) { ?>
        <ul class="author_pubproducts">
        <?php while ( $loop->have_posts() ) : $loop->the_post();
            woocommerce_get_template_part( 'content','product' );
        endwhile; ?>
        </ul>
        <?php
        } else {
            echo __( 'No products found','textdomain' );
        }
        wp_reset_postdata();
    ?>

希望它能正常工作

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...