How to list all products with total sales?

后端 未结 2 1565
礼貌的吻别
礼貌的吻别 2021-02-06 18:57

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.



        
2条回答
  •  被撕碎了的回忆
    2021-02-06 19:39

    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 '' . $output . '
    ' . __( 'Product', 'woocommerce' ) . '' . __( 'Units Sold', 'woocommerce' ) . '
    ';

提交回复
热议问题