WP - WooCommerce列出所有销售总额的产品

时间:2014-04-27 06:28:59

标签: wordpress woocommerce product sales

如何列出WooCommerce中所有产品的总销售额?此代码仅适用于1个产品。如果在$ product上放一个数组,那就不行了。

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

我想要输出,格式将是这样的:

[PRODUCT_NAME] - [TOTAL_SALES]

任何人都知道如何做到这一点?谢谢。 :)

2 个答案:

答案 0 :(得分:6)

为此,您可以使用标准get_posts()函数和自定义字段参数。 如果您希望让所有产品从arguments数组中删除元查询部分,则下面的示例将按降序排列销售额大于零的所有帖子。结果在HTML表格中格式化。

$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>';

答案 1 :(得分:4)

试试这段代码。它会以2格式提供输出

<?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>

希望这会有所帮助