WooCommerce后台如何仅保留商品页的wp_count_posts调用提升加载速度
根据调用栈可知,全后台触发wp_count_posts()的根源是WooCommerce初始化后台通知时,会调用WC_Install::is_new_install()方法统计商品数量判断站点是否为新安装状态,十万级商品场景下该统计查询耗时极高,拖慢所有后台页面加载。
你可以通过以下代码实现仅商品相关后台页面保留该调用,其余页面直接跳过统计:
// 拦截非商品页的WooCommerce商品数量统计调用 add_filter( 'pre_wp_count_posts', function( $counts, $type, $perm ) { // 仅拦截后台的product类型统计请求 if ( $type !== 'product' || ! is_admin() ) { return $counts; } $current_screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; if ( ! $current_screen ) { // 非后台页面渲染阶段直接返回假数据跳过查询 return (object) [ 'publish' => 1, 'draft' => 0, 'trash' => 0 ]; } // 允许触发统计的后台页面ID $allow_pages = [ 'edit-product', 'product', 'woocommerce_page_wc-products', 'woocommerce_page_wc-reports' ]; if ( ! in_array( $current_screen->id, $allow_pages, true ) ) { return (object) [ 'publish' => 1, 'draft' => 0, 'trash' => 0 ]; } return $counts; }, 10, 3 ); // 提前短路WooCommerce新安装判断,避免触发统计 add_filter( 'pre_option_woocommerce_is_new_install', function( $value ) { if ( ! is_admin() ) { return $value; } $current_screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; if ( ! $current_screen ) { return 'no'; } $allow_pages = [ 'edit-product', 'product', 'woocommerce_page_wc-products', 'woocommerce_page_wc-reports' ]; if ( ! in_array( $current_screen->id, $allow_pages, true ) ) { return 'no'; } return $value; } );
配置说明
- 代码中
$allow_pages数组存储的是允许触发统计的后台页面ID,你可以根据自身需求增减,比如要在订单页也保留的话,新增对应screen ID即可 - 代码兼容WordPress 5.6及以上版本、所有主流WooCommerce版本,升级插件后如果失效可重新核对调用栈调整钩子即可
- 若站点已开启对象缓存,可额外给
wp_count_posts的查询结果增加12-24小时缓存,进一步降低数据库压力
内容的提问来源于stack exchange,提问作者Jordan Carter
相关产品推荐
相关产品推荐

