Search code examples
phpwordpresswoocommerceproductauthor

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?


Solution

  • 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