How to list all products from WooCommerce with total sales? This code is just for 1 product only. It\'s not work if put an array on $product.
For that you can use standard get_posts() function with custom field parameters. The example below will take all posts with sales greater than zero in a descending order, if you want to get all products remove the meta query part from the arguments array. The result is formatted in a HTML table.
$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 .= '' . $post->post_title . ' ' . get_post_meta( $post->ID, 'total_sales', true ) . ' ';
} );
echo '' . __( 'Product', 'woocommerce' ) . ' ' . __( 'Units Sold', 'woocommerce' ) . ' ' . $output . '
';