通过短代码实现调用woocommerce本月关注度最高(浏览量最高)的商品

WooCommerce自带的[products]短代码没有直接按“浏览量”排序的参数,因此无法仅通过一段官方短代码就“本月浏览量最高”的商品。

要实现这一需求,必须满足下面两个前提:

网站安装了统计浏览量的插件(例如PostViewsCounter、WPPostViews、JetpackStats等),并且把每天的浏览量写入了一个自定义字段,常见的字段名叫post_views或_views_count。

用几行PHP把WooCommerce短代码查询改写成按这个自定义字段、且限定“本月时间范围”排序。

把下面代码一次性放进主题(或子主题)的functions.php,即可在页面/文章里直接用短代码:

/**
 * 短代码 [most_viewed_this_month] 展示本月浏览量最高的商品
 * 用法示例:[most_viewed_this_month limit="6" columns="3"]
 */
add_shortcode( 'most_viewed_this_month', 'shortcode_most_viewed_this_month' );
function shortcode_most_viewed_this_month( $atts ) {
    $atts = shortcode_atts( [
        'limit'   => 4,
        'columns' => 4,
        'meta_key'=> 'post_views', // 按你实际插件生成的字段名修改
    ], $atts, 'most_viewed_this_month' );

    // 本月第一天 00:00:00
    $month_start = date( 'Y-m-01 00:00:00' );

    $query_args = [
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'posts_per_page' => (int)$atts['limit'],
        'meta_key'       => $atts['meta_key'],
        'orderby'        => 'meta_value_num',
        'order'          => 'DESC',
        'date_query'     => [
            'after' => $month_start,
        ],
        'tax_query'      => [  // 排除非公开商品
            [
                'taxonomy' => 'product_visibility',
                'field'    => 'name',
                'terms'    => 'exclude-from-catalog',
                'operator' => 'NOT IN',
            ],
        ],
    ];

    $products = new WP_Query( $query_args );
    if ( ! $products->have_posts() ) {
        return '<p>暂无数据</p>';
    }

    // 使用 WooCommerce 自带模板输出
    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();

    // 用 WooCommerce 自带 grid 包装
    $loop_html = '<div class="woocommerce columns-' . absint( $atts['columns'] ) . '">' .
                 ob_get_clean() . '</div>';

    return $loop_html;
}

使用方法(短代码)

[most_viewed_this_month limit="6" columns="3"]

即可在任意文章、页面、小工具或Elementor/HTML模块里直接调用,显示本月浏览量最高的6个商品,3列排版。