WooCommerce获取30天内销售最多的产品

建站知识 2025年7月31日

在WooCommerce里,WooCommerce本身并没有一个现成的短代码能直接“列出最近30天内销量最高的前N个商品”。要实现这个功能,最干净、可复用的做法是自己写一个自定义短代码。以下是一段可直接放到主题(或子主题)的functions.php、或做成一个小插件的代码,它会注册一个短代码:

/**
 * 短代码 [top_sellers_30days] 列出过去 30 天销量最高的商品
 * 用法: [top_sellers_30days per_page="12" columns="4"]
 */
add_shortcode( 'top_sellers_30days', 'wc_top_sellers_30days_shortcode' );
function wc_top_sellers_30days_shortcode( $atts ) {

    // 默认参数
    $atts = shortcode_atts( array(
        'per_page' => 12,
        'columns'  => 4,
    ), $atts, 'top_sellers_30days' );

    // 计算 30 天前的时间戳
    $from_date = date( 'Y-m-d', strtotime( '-30 days' ) );

    // 查询条件
    $args = array(
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'posts_per_page' => intval( $atts['per_page'] ),
        'meta_key'       => 'total_sales',
        'orderby'        => 'meta_value_num',
        'order'          => 'DESC',
        'date_query'     => array(
            array(
                'after'     => $from_date,
                'inclusive' => true,
            ),
        ),
        'tax_query'      => array(
            array(
                'taxonomy' => 'product_type',
                'field'    => 'slug',
                'terms'    => array( 'simple', 'variable', 'grouped' ), // 排除外部/联盟商品
            ),
        ),
    );

    $products = new WP_Query( $args );

    if ( ! $products->have_posts() ) {
        return '<p>暂无热销商品。</p>';
    }

    // 使用 WooCommerce 自带的 product loop 模板
    ob_start();

    woocommerce_product_loop_start();

    while ( $products->have_posts() ) {
        $products->the_post();
        wc_get_template_part( 'content', 'product' );
    }

    woocommerce_product_loop_end();

    wp_reset_postdata();

    return '<div class="woocommerce columns-' . esc_attr( $atts['columns'] ) . '">' . ob_get_clean() . '</div>';
}

使用方法

把上面代码放进主题的functions.php或做成一个小插件(推荐用CodeSnippets插件)。

在页面/文章/小工具里直接写:

[top_sellers_30days per_page="12" columns="4"]

即可得到“最近30天内销量最高的12个商品”,且样式与商店列表页完全一致,支持主题响应式布局。