Woocommerce get all products in array

Im having problems with retrieving product infos trough object functions in Woocommerce.

This is how I do:

Read More
public function table_data()
{
    $args     = array( 'post_type' => 'product', 'posts_per_page' => -1 );
    $products = get_posts( $args );

    $pfactory = new WC_Product_Factory();
    foreach($products as $product)
    {
        $_product = $pfactory->get_product($product);
    }
}

This returns product informations from wp_posts only, it won’t give me the information stored in wp_postmeta.

I need the full information from all products (such as price, sku, stock etc.) in one array, but I seem to be missing something and Im unsure if it has with the hierarchy of the functions in my code. However I thought this was possible to do without SQL-queries.

Basicly, what im trying to do is a complete duplicate of product list in admin for listing products with information in the panel.

Thanks for all the help I can get.

Related posts

Leave a Reply

3 comments

  1. Use WP_Query instead, which will give you access to the global WooCommerce $product variable from within the loop. From there, you can grab the price, sku, stock and all other kinds of data. http://docs.woothemes.com/wc-apidocs/class-WC_Product.html

    <?php
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1
        );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ): while ( $loop->have_posts() ): $loop->the_post();
    
            global $product;
    
            $price = $product->get_price_html();
            $sku = $product->get_sku();
            $stock = $product->get_stock_quantity();
    
        endwhile; endif; wp_reset_postdata();
    ?>
    
  2. First thing I came up with was this.

    function products() {
            return array_map('wc_get_product', get_posts(['post_type'=>'product','nopaging'=>true]));
    }
    

    I’d love to know from someone more experienced with WooCommerce if there is a better way

  3. As of WooCommerce 3 you can do it using the wc_get_products function like this:

      $args = array(
        'status' => 'publish',
        'orderby' => 'title',
        'order' => 'ASC',
        'limit' => -1,
      );
      $products = wc_get_products($args);
      if (count($products) > 0) {
        foreach ($products as $product) {
          echo $product->get_id() . '<br>';
          echo $product->get_name() . '<br>';
          echo $product->get_price_html() . '<br>';
          echo $product->get_sku() . '<br>';
          echo $product->get_stock_quantity() . '<br>';
        }
      }