Using WooCommerce, I have this code that output a product list report:
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'total_sales',
'value' => 0,
'compare' => '>'
)
)
);
$output = array_reduce( get_posts( $args ), function( $result, $post ) {
return $result .= '<tr><td>' . $post->post_title . '</td><td>' . get_post_meta( $post->ID, 'total_sales', true ) . '</td></tr>';
} );
echo '<table><thead><tr><th>' . __( 'Product', 'woocommerce' ) . '</th><th>' . __( 'Units Sold', 'woocommerce' ) . '</th></tr></thead>' . $output . '</table>';
With that code I would like to list the sales on a Wordpress page.
My question: How to add the SKU to the table?
Thanks
— Light Update —
You can add the sku changing a little bit your code this way:
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'total_sales',
'value' => 0,
'compare' => '>'
)
)
);
$output = array_reduce( get_posts( $args ), function( $result, $post ) {
return $result .= '
<tbody>
<tr>
<td>' . $post->post_title . '</td>
<td>' . get_post_meta( $post->ID, "total_sales", true ) .'</td>
<td>' . get_post_meta( $post->ID, "_sku", true ) .'</td>
</tr>
</tbody>';
} );
echo '<table>
<thead>
<tr>
<th>' . __( "Product", "woocommerce" ) . '</th>
<th>' . __( "Units Sold", "woocommerce" ) . '</th>
<th>' . __( "Sku", "woocommerce" ) . '</th>
</tr>
</thead>' . $output . '
</table>';
I am using here get_post_meta( $post->ID, "_sku", true )
to get the SKU value from wp_postmeta database table…
Or alternatively you can use with a product object the method get_sku()
…