skip to Main Content

Can you tell me how to display all the products of a certain user (the one who added the product) Woocommerce using a shortcode? I almost managed to create this code, but it gives this error:

Warning: Array to string conversion in /var/www/

What am I doing wrong?

add_shortcode( 'author_products', 'products_current_author' );
 
function products_current_author() {
$args = [
    'author_name'    => 'andrey',
    'post_type' => 'product',
    'posts_per_page' => - 1,
    'fields'         => 'ids',
];

$ids[] = get_posts( $args );
    
    
    return do_shortcode( '[products ids="' . join( ",", array_unique( $ids) ) . '"]' );
 
}

2

Answers


  1. Chosen as BEST ANSWER

    I managed to solve my problem on my own. Here is the working code, tested, working.

    add_shortcode( 'author_products', 'author_products_shortcode' );
       
    function author_products_shortcode() {
    // Get the author ID Outside loop.
        global $post;
        $author_id = $post->post_author;
    
       $args = array(
          'author'    => $author_id,
          'post_type' => 'product',
          'posts_per_page' => -1,
          'post_status' => 'publish',
          'fields' => 'ids',
       );
        
       $product_ids = get_posts( $args ); 
       $product_ids = implode( ",", $product_ids );
        
       return do_shortcode("[products ids='$product_ids']");
     
    }
    
    

  2. According to provided code, to display all products by product author, using woocommerce, the following code can be checked:

    add_shortcode( 'author_products', 'products_current_author' );
    function products_current_author() {
        $args = [
            'author_name'    => 'andrey',
            'post_type' => 'product',
            'posts_per_page' => - 1,
            'fields'         => 'ids',
        ];
        $ids = get_posts( $args );
        echo do_shortcode( '[products ids="' . join( ",", array_unique( $ids) ) . '"]' ); 
    }
    

    It can be checked, if this code works.

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