문제

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]
도움이 되었습니까?

해결책 2

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

다른 팁

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 .= '<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>';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top