Tuesday, May 10, 2022

[FIXED] How to list all products with total sales?

Issue

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.

<?php
$product = "13";
$units_sold = get_post_meta( $product, 'total_sales', true );
echo '<p>' . sprintf( __( 'Units Sold: %s', 'woocommerce' ), $units_sold ) . '</p>';
?>

I want on output, format will be like this:

[PRODUCT_NAME] - [TOTAL_SALES]

Solution

Try this code. It'll give you output in 2 format

<?php
global $wpdb;
$results = $wpdb->get_results("SELECT p.post_title as product, pm.meta_value as total_sales FROM {$wpdb->posts} AS p LEFT JOIN {$wpdb->postmeta} AS pm ON (p.ID = pm.post_id AND pm.meta_key LIKE 'total_sales') WHERE p.post_type LIKE 'product' AND p.post_status LIKE 'publish'", 'ARRAY_A');
?>
<table>
    <tr>
        <th><?php _e( 'Product' ); ?></th>
        <th><?php _e( 'Unit sold' ); ?></th>
    </tr>
<?php
foreach ( $results as $result ) {
    echo "<tr>";
    echo "<td>" . $result['product'] . "</td>";
    echo "<td>" . $result['total_sales'] . "</td>";
    echo "</tr>";
}
?>
</table>
<div>
    <p><strong><?php echo __( 'Product' ) . ' - ' . __( 'Unit Sold' ); ?></strong></p>
    <?php
    foreach ( $results as $result ) {
        echo "<p>" . $result['product'] . ' - ' . $result['total_sales'] . "</p>";
    }
    ?>
</div>

Hope this will be helpful



Answered By - Ratnakar - StoreApps
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.