php 只显示 if 循环的最后结果

php display only the last result of a if loop

我在我的网站上使用循环来显示当前 post.

的前一个 post permalinks
<?php
global $post;
$current_post = $post;
for($i = 1; $i <= 30; $i++):
$post = get_previous_post();
setup_postdata($post); ?>

<?php if($post): ?>

<a href="<?php the_permalink(); ?>" title="post-<?php the_ID(); ?>" class="next_link">Next Posts</a>

<?php endif; ?>
<?php endfor;
wp_reset_postdata();
$post = $current_post; 
?>

使用这个循环我得到了 "next posts" link 的 30 倍。 我想做的是只得到这个循环的最后结果。

目前,我使用 css 和 jquery 仅显示最后一个 link,使用此 css :

a.next_link {display:none}
a.next_link:last-child {display: block}

但你可以想象这不是一个好的解决方案。

我想 运行 循环并且只得到最后一个 $post.

有没有办法在我的循环中添加一些 php 以仅获取此循环的最后一个 $post?

感谢您的帮助,

您要做的是跳过前面的 29 个条目,因为 WP 没有提供开箱即用的方法。使用 continue 来操纵你的循环。

<?php
global $post;
$current_post = $post;
for($i = 1; $i <= 30; $i++):
$post = get_previous_post();
if ($i != 30):
  continue;
endif;
setup_postdata($post); ?>

<?php if($post): ?>

<a href="<?php the_permalink(); ?>" title="post-<?php the_ID(); ?>" class="next_link">Next Posts</a>

<?php endif; ?>
<?php endfor;
wp_reset_postdata();
$post = $current_post; 
?>