【问题标题】:Get products by author id using a WC_Query in WooCommerce?在 WooCommerce 中使用 WC_Query 按作者 ID 获取产品?
【发布时间】:2020-08-17 12:25:20
【问题描述】:

我尝试在 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()) );

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

【问题讨论】:

    标签: php wordpress woocommerce product author


    【解决方案1】:

    您可以使用未记录的参数“author”在 WC_Query 中按作者 ID 简单地获取产品,如下所示:

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

    你会得到一个WC_Product对象的数组

    【讨论】:

    • LoicTheAztec,拯救天使。十分感谢。我本末倒置。
    【解决方案2】:

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

    <?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();
        ?>
    

    希望成功

    【讨论】:

    • 非常感谢,但我想获得 wc_get_products 输出。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2019-03-03
    • 2016-03-04
    相关资源
    最近更新 更多