WordPress循环(我想),我需要第5个做不同的事情

Dav*_*llo 0 php wordpress loops

我不太了解PHP,所以我希望在提出这个问题时我会展示足够的代码.我的主页的一部分将显示最新的5篇博文,因此我将其设置为:

<?php
function get_latest_post_html() {
    $content = "";
    query_posts('showposts=5');
    while (have_posts()){
        the_post();
        $content .= "<p class='title'><a href='" . get_permalink() . "'>" . get_the_title() . "</a></p>\n" .
                "<p class='excerpt'><a href='" . get_permalink() . "'><img src='" . wp_get_attachment_url( get_post_thumbnail_id($post->ID) ) . "' class='rt-image img-left wp-post-image' style='max-width:175px;'/></a>" . get_the_excerpt() . "</p><br/><hr/>";
    }
    wp_reset_query();

    return "<div class='latest-post'>\n$content\n</div>";
}

add_shortcode('get_latest_post', 'get_latest_post_html');
?>
Run Code Online (Sandbox Code Playgroud)

它称最后5个帖子就好了,但我不想让它显示<hr/>在第5个帖子的底部.

Jas*_*ary 5

while循环中设置一些逻辑以有条件地显示<hr >.

例如:

$i = 0;
while (have_posts()) {
  ++$i;
  the_post();

  // ...

  if ($i < 5) {
    $content .= '<hr />';
  }
}
Run Code Online (Sandbox Code Playgroud)

注意: WordPress可能不会返回5个帖子,因此您应该考虑该路径.我也会在紧密的循环中阻止字符串连接.重构您的代码并使用echo.