skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search