Getting the Product object in a custom loop

I am currently building a Theme for a site that is using WooCommerce to provide a Shop to Customers. I have just started on it, and I am currently working on the Product Category pages. I have hit a road block trying to fetch the WooCommerce Product object.

I have read that using the variable global $product should return the WC_Product object, but when I do the_post(); var_dump($product), NULL is returned.

Read More

I tried to then create a Product object by doing the_post(); $product = new WC_Product(get_the_ID()), but when I did the var_dump($product) on that, it gave me general information about the product (post_name, post_description, etc), but nothing further than if I called get_post().

Can someone tell me what I have missed please?

Related posts

2 comments

  1. You could use a custom query to fetch the product object. Here is a snippet to get the stock count. Take a look at the product class: http://docs.woothemes.com/wc-apidocs/class-WC_Product.html for functions available for the product object.

    <?php $args = array(
                'post_type'         => 'product',
                'post_status'       => 'publish',
                'posts_per_page'    => -1,
                'orderby'           => 'title',
                'order'             => 'ASC',               
                'tax_query' => array(
                    array(
                        'taxonomy'  => 'product_type',
                        'field'     => 'slug',
                        'terms'     => array('simple'),
                        'operator'  => 'IN'
                    )
                )
            );
    
            $loop = new WP_Query( $args );
            $stock_count = array();
            while ( $loop->have_posts() ) : $loop->the_post();
    
                            global $product;
                            $stock_count[] = $product->get_stock_quantity();
    
            endwhile; 
    
    
            // count the array values and output them
            echo "<h2>Stock Count: ".array_sum($stock_count)."</h2>";
            ?>
    
  2. Sorry, I have almost instantly found the solution. Thought about deleting the question, but in case others have the same problem, I will leave it here.

    To get the Product object with all the required attributes, you need to call get_product() after the_post(), and that will return the Product object for you to use.

Comments are closed.