I am trying to produce a report of products and their quantities. All works fine except for the variable products, I'm having a hard time getting the quantity...this is what I have so far:
global $wpdb;
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'nopaging' => 'true',
'orderby' => 'post_title',
'order' => 'asc'
);
$loop = new WP_Query( $args );
$output = '<div style="float: right;">As of ' . current_time('F d, Y h:ia') . '</div>';
$output .= '<h3>Products Report</h3>';
$output .= '<table border="0"><tbody>';
while ( $loop->have_posts() ) : $loop->the_post();
$product = new WC_Product( $loop->post->ID );
if ($product->product_type == 'variable') {
$product = new WC_Product_Variable( $loop->post->ID );
}
$qty = ($product->get_total_stock() != 0) ? $product->get_total_stock(): 'OUT';
$price = '$'.$product->get_price();
$output .= '<tr><td><em><strong>' . $loop->post->post_title . '</strong></em><br>' . $loop->post->post_content . '</td><td><span class="wc-qty">' . $qty .'</span></td><td>' . $price .'</td></tr>';
endwhile;
$output .= '</tbody></table>';
echo $output;
The $product->product_type is returning nothing, blank. How can I get the variations information for a variable products?
I don't think you need to do anything special to create a variable product object. That should work the same as the others. I've swapped some of your functions out for updated WooCommerce product methods, I haven't tested it so, I can't be sure if this does what you're after:
while ( $loop->have_posts() ) : $loop->the_post();
$product = wc_get_product( get_the_ID() ) );
$qty = ($product->get_total_stock() > 0) ? $product->get_total_stock(): 'OUT';
$price = $product->get_price_html();
$output .= '<tr><td><em><strong>' . $product->get_title() . '</strong></em><br>' . $loop->post->post_content . '</td><td><span class="wc-qty">' . $qty .'</span></td><td>' . $price .'</td></tr>';
endwhile;