You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery点击show more每次加载2篇文章 按钮仅单次生效问题解决

问题根因

你当前代码失效的核心原因是没有动态跟踪已加载的文章数量,每次点击都调用固定区间的slice方法,首次执行后符合区间的文章已经全部展示,后续点击拿不到新的隐藏文章节点,所以没有响应。

修复后的jQuery代码示例
jQuery(function($){
  // 初始已加载的文章数,和PHP默认渲染的展示数量保持一致
  let loadedNum = 2;
  // 总文章数,从按钮的data属性读取,PHP渲染时赋值
  const totalPosts = $('.show-more-btn').data('total');

  $('.show-more-btn').on('click', function(){
    // 每次取前2个未展示的文章项
    const $hiddenPosts = $('.custom-post-item:hidden').slice(0, 2);
    // 展示选中的文章
    $hiddenPosts.fadeIn();
    // 更新已加载数
    loadedNum += $hiddenPosts.length;
    // 全部加载完成后隐藏按钮
    if(loadedNum >= totalPosts){
      $(this).hide();
    }
  })
})
WordPress PHP渲染调整要求

你需要调整原自定义文章查询的渲染逻辑,适配前端逻辑:

  • 给所有文章项加统一类名custom-post-item,默认只展示前2篇,剩余文章加行内样式style="display:none;"或者自定义隐藏类
  • 给show more按钮加存储总文章数的data属性,示例如下:
<?php
$args = [
  'post_type' => '你的自定义文章类型别名',
  'posts_per_page' => -1, // 一次性查询所有文章,前端做懒加载
];
$custom_query = new WP_Query($args);
if($custom_query->have_posts()):
  $index = 0;
  while($custom_query->have_posts()): $custom_query->the_post();
    $style = $index < 2 ? '' : 'style="display:none;"';
    echo '<div class="custom-post-item" '.$style.'>';
    // 这里放你原有的文章内容渲染代码
    echo '</div>';
    $index++;
  endwhile;
  // 总文章数大于初始展示数才显示加载按钮
  if($custom_query->post_count > 2):
?>
<button class="show-more-btn" data-total="<?php echo $custom_query->post_count; ?>">Show More</button>
<?php
  endif;
  wp_reset_postdata();
endif;
?>
额外优化说明

如果你的文章数量较多,不建议一次性查询所有文章,可以改为AJAX请求加载后续文章,避免首次页面加载资源过多。

内容的提问来源于stack exchange,提问作者Roberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:15:03