WooCommerce点击分页后滚动至顶部问题及无效代码求助
WooCommerce分页后自动滚动到顶部的解决方案
你之前的代码仅针对带swoof参数的场景,且依赖固定延迟,容易因DOM加载时机不对或场景覆盖不全导致无效。以下是更可靠的解决方案:
1. 普通分页场景(页面刷新式分页)
适用于WooCommerce原生的商店、商品分类/标签页分页,切换到第2页及以后时,页面加载完成后自动滚动到顶部:
add_action('wp_footer', 'wc_pagination_scroll_to_top'); function wc_pagination_scroll_to_top() { // 仅在商品归档页生效 if ( is_shop() || is_product_category() || is_product_tag() ) { $current_page = get_query_var('paged', 1); // 仅当前页大于1时执行滚动 if ( $current_page > 1 ) { ?> <script> document.addEventListener('DOMContentLoaded', function() { window.scrollTo({ top: 0, behavior: 'smooth' }); }); </script> <?php } } }
2. AJAX分页/筛选场景(如SWOOF插件)
如果是AJAX加载的分页或筛选结果,需要监听对应的AJAX完成事件,确保内容加载后再滚动:
add_action('wp_footer', 'wc_ajax_pagination_scroll_to_top'); function wc_ajax_pagination_scroll_to_top() { if ( is_shop() || is_product_category() || is_product_tag() ) { ?> <script> // 监听WooCommerce原生AJAX商品加载完成事件 jQuery(document).on('woocommerce_product_loop_end', function() { jQuery('html, body').animate({ scrollTop: 0 }, 700); }); // 针对SWOOF筛选插件的AJAX完成事件,滚动到筛选面板区域 jQuery(document).on('swoof:ajax:done', function() { setTimeout(function() { var target = jQuery(".woof_products_top_panel_content"); if (target.length) { jQuery('html, body').animate({ scrollTop: target.offset().top - 100 }, 700); } else { // 目标元素不存在时默认滚到顶部 jQuery('html, body').animate({scrollTop: 0}, 700); } }, 100); }); </script> <?php } }
关键优化点
- 用
DOMContentLoaded或插件原生事件替代固定延迟,确保DOM元素加载完成后再执行滚动 - 增加目标元素存在性判断,避免元素不存在时出错
- 覆盖普通分页和AJAX分页两种场景,适配更多使用情况
将上述代码替换你原有的代码,添加到主题的functions.php文件中即可。
内容的提问来源于stack exchange,提问作者eMikkelsen
相关产品推荐
相关产品推荐

