WordPress中用PHP、jQuery实现单页应用点击切换单篇文章展示功能
实现方案
一、解决文章堆叠、单次仅展示1篇可切换的需求
你现在所有文章堆叠是因为while循环直接把所有符合条件的文章都输出到了DOM中,对于你限制最多拉取8篇($i<9)的场景,推荐直接把所有文章数据预存在前端,通过JS控制切换,不需要额外发请求,实现逻辑如下:
首先修正不推荐的query_posts写法,调整PHP逻辑:
<?php $wp_query = new WP_Query( $args ); $count = $wp_query->post_count; $post_list = []; if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post(); // 存入需要的所有字段 $post_list[] = [ 'index' => $wp_query->current_post + 1, 'title' => get_the_title(), 'content' => get_the_content(), 'slug' => $post->post_name, ]; endwhile; wp_reset_postdata(); // 重置主查询数据,避免影响其他循环 endif; ?> <!-- 文章展示容器 --> <div class="post-wrap"> <div class="post-count"><?php echo $post_list[0]['index'] . ' / ' . $count; ?></div> <h1 class="post-title"><?php echo $post_list[0]['title']; ?></h1> <div class="post-content"><?php echo $post_list[0]['content']; ?></div> </div> <!-- 切换按钮 --> <button id="prev-btn">上一篇</button> <button id="next-btn">下一篇</button> <!-- 前端切换逻辑 --> <script> // 注入预加载的文章数据 const allPosts = <?php echo json_encode($post_list); ?>; let currentPostIndex = 0; const postTotal = allPosts.length; // 下一篇逻辑 document.querySelector('#next-btn').addEventListener('click', () => { if(currentPostIndex >= postTotal - 1) return; currentPostIndex++; renderPost(); }); // 上一篇逻辑 document.querySelector('#prev-btn').addEventListener('click', () => { if(currentPostIndex <= 0) return; currentPostIndex--; renderPost(); }); // 公共渲染方法 function renderPost() { const post = allPosts[currentPostIndex]; document.querySelector('.post-count').textContent = `${post.index} / ${postTotal}`; document.querySelector('.post-title').textContent = post.title; document.querySelector('.post-content').innerHTML = post.content; // 如果需要同步修改URL为当前文章slug无刷新跳转,可开启下面一行 // history.pushState({}, '', window.location.origin + '/' + post.slug); } </script>
如果你的文章数量较多,不适合预加载所有数据,可以在切换按钮点击时通过AJAX请求对应slug的文章数据再渲染,逻辑和上面的render方法类似。
二、正确获取相邻文章slug的方法
WordPress没有内置get_slug方法,你之前的写法报错是因为调用了不存在的函数,正确获取相邻文章slug的代码如下:
// 获取下一篇文章 $next_post = get_adjacent_post(false, '', false); $next_slug = !empty($next_post) ? $next_post->post_name : ''; // 获取上一篇文章 $prev_post = get_adjacent_post(false, '', true); $prev_slug = !empty($prev_post) ? $prev_post->post_name : '';
拿到slug之后你可以直接传入AJAX接口查询对应文章,或者拼接成你需要的路径使用。
内容的提问来源于stack exchange,提问作者dsmscholl
相关产品推荐
相关产品推荐

