WooCommerce统计符合日期规则的指定产品有效订阅数
WooCommerce 订阅统计功能实现
需求说明
- 基于WooCommerce Subscriptions插件实现定向订阅统计
- 统计产品范围:ID为
10800、15340的两款商品 - 筛选规则:仅统计状态为有效、结束日期不早于下月1日(固定每月1日为同步执行日)的订阅,无固定结束日期的永久有效订阅默认纳入统计
- 展示位置:WordPress后台订阅管理列表页(路径:
/wp-admin/edit.php?post_type=shop_subscription)顶部
实现代码
将以下代码添加到当前主题的functions.php文件,或者自定义功能插件中即可生效:
/** * 统计符合筛选规则的目标订阅 */ function get_valid_target_subscriptions() { global $wpdb; // 基础配置项 $target_product_ids = [10800, 15340]; // 生成下月1日0点时间戳作为筛选阈值 $threshold_timestamp = strtotime(date('Y-m-01 00:00:00', strtotime('+1 month'))); // 生成SQL预处理占位符 $product_placeholders = implode(',', array_fill(0, count($target_product_ids), '%d')); $query = $wpdb->prepare( "SELECT p.ID, p.post_title, pm_end.meta_value as end_timestamp, woi.order_item_name, woim_qty.meta_value as item_qty FROM {$wpdb->prefix}posts p LEFT JOIN {$wpdb->prefix}woocommerce_order_items woi ON p.ID = woi.order_id LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta woim_pid ON woi.order_item_id = woim_pid.order_item_id LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta woim_qty ON woi.order_item_id = woim_qty.order_item_id LEFT JOIN {$wpdb->prefix}postmeta pm_end ON p.ID = pm_end.post_id AND pm_end.meta_key = '_schedule_end' WHERE p.post_type = 'shop_subscription' AND p.post_status = 'wc-active' AND woim_pid.meta_key = '_product_id' AND woim_pid.meta_value IN ({$product_placeholders}) AND woim_qty.meta_key = '_qty' AND (pm_end.meta_value >= %d OR pm_end.meta_value = 0) GROUP BY p.ID", array_merge($target_product_ids, [$threshold_timestamp]) ); return $wpdb->get_results($query); } /** * 在订阅列表页顶部输出统计面板 */ add_action('admin_notices', function() { global $pagenow, $post_type; // 仅在指定订阅列表页加载统计逻辑 if ($pagenow !== 'edit.php' || $post_type !== 'shop_subscription') return; $sub_list = get_valid_target_subscriptions(); $total_qty = 0; foreach ($sub_list as $item) { $total_qty += intval($item->item_qty); } ?> <div class="notice notice-info"> <p><strong>下月同步有效订阅统计(目标产品ID:10800、15340)</strong></p> <p>符合条件的有效订阅总份数:<?php echo esc_html($total_qty); ?></p> <?php if (!empty($sub_list)) : ?> <table class="widefat fixed" style="margin: 10px 0;"> <thead> <tr> <th>订阅ID</th> <th>订阅名称</th> <th>对应商品</th> <th>订购数量</th> <th>订阅结束日期</th> </tr> </thead> <tbody> <?php foreach ($sub_list as $sub) : ?> <tr> <td>#<?php echo esc_html($sub->ID); ?></td> <td><?php echo esc_html($sub->post_title); ?></td> <td><?php echo esc_html($sub->order_item_name); ?></td> <td><?php echo esc_html($sub->item_qty); ?></td> <td><?php echo intval($sub->end_timestamp) === 0 ? '永久有效' : esc_html(date('Y-m-d', $sub->end_timestamp)); ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif; ?> </div> <?php });
代码说明
- 修正了原有参考代码的语法错误,使用WP官方推荐的
$wpdb->prepare()方法做参数转义,避免SQL注入风险 - 去掉冗余的表关联逻辑,直接对接订阅主表查询,执行效率更高
- 自动计算下月1日的时间戳作为筛选阈值,无需手动调整日期参数
- 统计面板同时展示总份数和订阅明细,包含订阅ID、对应商品、数量、结束日期信息,永久有效订阅会做单独标注
- 增加页面判断逻辑,仅在指定的订阅列表页加载统计代码,不影响其他后台页面的加载速度
内容的提问来源于stack exchange,提问作者Nik7
相关产品推荐
相关产品推荐

