Web Design
Web Design

Reputation: 105

Get products by author id using a WC_Query in WooCommerce?

I trying to get products by post author id using a WC_Query in WooCommerce, so I tried to include a new custom meta_key "_author", with the following:

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;
}

Then I tried to use it with wc_get_products():

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

but it return null array. Any idea?

Upvotes: 2

Views: 5706

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253959

You can simply get products by author Id in a WC_Query using the undocumented parameter "author'" as follow:

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

You will get an array of WC_Product Objects

Upvotes: 6

SolverWp
SolverWp

Reputation: 41

You can use custom query like this

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

Hope it's work

Upvotes: 2

Related Questions