2

我所拥有的是一个页面,它显示了一个类别的帖子,底部有一个上一个和下一个帖子链接。我遇到的问题是,当它到达最后一个时,我想循环回到起点。如果您在第一个帖子上,它会一直运行到最后,如果您在最后一个帖子上,它不会回到开头,如果您在最后一个帖子上,它只会显示最后一个帖子。

到目前为止,这是我的代码:

<?php 
$prev_post = get_adjacent_post( true, '', true );
$next_post = get_adjacent_post( true, '', false );
$prev_post_id = $prev_post->ID;
$next_post_id = $next_post->ID;
?>

<?php if ($prev_post_id == '') {
$query = new WP_Query( array ( 'orderby' => 'ASC', 'posts_per_page' => '1', 'cat=4' ));

  while($query->have_posts()):
       $query->the_post();
       $prev_post_id = $query->post->ID;
  endwhile;
} ?>
<?php if ($next_post_id == '') {
  $query2 = new WP_Query( array ( 'orderby' => 'DESC', 'posts_per_page' => '1', 'cat=4'    ));
  while($query2->have_posts()):
       $query2->the_post();
       $next_post_id = $query2->post->ID;
  endwhile;
} ?>

<a href="<?php echo get_permalink($prev_post_id); ?>" class="prev-footer-item">
  <div class="prev-inner">
    <h3 class="gamma"><?php echo get_the_title($prev_post_id ); ?></h3>
    <h4 class="delta"><?php the_field('subtitle', $prev_post_id ); ?></h4>
    <div class="footer-overlay"></div>
  </div>
 </a>
<a href="<?php echo get_permalink($next_post_id); ?>" class="next-footer-item">
  <div class="next-inner">
    <h3 class="gamma"><?php echo get_the_title($next_post_id); ?></h3>
    <h4 class="delta"><?php the_field('subtitle', $next_post_id); ?></h4>
    <div class="footer-overlay"></div>
  </div>
</a>

我敢肯定,我很明显错过了一些东西,对吧?

更新:工作上一篇文章:

[request] => SELECT SQL_CALC_FOUND_ROWS  as1_posts.ID FROM as1_posts  WHERE 1=1  AND as1_posts.post_type = 'post' AND (as1_posts.post_status = 'publish' OR as1_posts.post_status = 'private')  ORDER BY as1_posts.post_date DESC LIMIT 0, 1

不工作 下一篇文章:

[request] => SELECT SQL_CALC_FOUND_ROWS  as1_posts.ID FROM as1_posts  WHERE 1=1  AND as1_posts.post_type = 'post' AND (as1_posts.post_status = 'publish' OR as1_posts.post_status = 'private')  ORDER BY as1_posts.post_date DESC LIMIT 0, 1
4

1 回答 1

0

我看不到任何对我跳出的东西,但是我已经在if你的两个循环中添加了一个语句(以防止错误),wp_reset_postdata()在每个循环之后添加,并且不再需要$queryand $query2- 你可以只使用$queryfor 两个 if您不希望将查询结果用于除此之外的任何内容。

另一个想法 -如果 Post ID 不存在,您是否确定get_adjacent_post()返回?''可能是null,或者'0'例如。可能值得做var_dump($next_post_id)和检查。

编辑

我忘了提及,get_adjacent_post()假设post_type相邻帖子的 与您当前正在查看的帖子相同。不过,我不认为这是一个问题,正如您已经说过的那样,它可以反过来工作,但这是未来要记住的事情。

<?php
if($prev_post_id === '') :

    $query = new WP_Query(array('orderby' => 'ASC', 'posts_per_page' => '1', 'cat=4'));

    if($query->have_posts()) : while($query->have_posts()) :
        $query->the_post();
        $prev_post_id = get_the_ID();
        endwhile;
    endif;

    wp_reset_postdata();

endif;

if($next_post_id === '') :

    $query = new WP_Query(array('orderby' => 'DESC', 'posts_per_page' => '1', 'cat=4'));

    if($query->have_posts()) : while($query->have_posts()) :
            $query->the_post();
            $next_post_id = get_the_ID();
        endwhile;
    endif;

    wp_reset_postdata();

endif;
?>
于 2012-11-22T11:42:48.273 回答