"endwhile;"和"endif;"这两个术语应该放在哪里?



作为PHP编码的相对新手,我目前依靠YouTube教程,以帮助我从头开始创建WordPress主题。

我想使用PHP插入页面内容下的博客文章的地步。遵循YouTube教程,我创建了以下代码:

<?php       
    $lastBlog = new WP_Query('type=post&posts_per_page=1&category_name=news');
        if ( $lastBlog->have_posts() ):
            while( $lastBlog->have_posts() ): $lastBlog->the_post(); 
    ?>
        <?php get_template_part('content/content',get_post_format()); 
        ?>
    <?php 
            endwhile;
        endif;                  
    wp_reset_postdata();
    ?>

上述代码正确吗?我不是100%,因为我的逻辑心态告诉我"最终";和" endif;"语句应放置在以下之间:

之间
        while( $lastBlog->have_posts() ): $lastBlog->the_post();
    ?>

,如果有人能够澄清此事,这将非常有帮助。

非常感谢。

craig

在PHP中,没有规则或实践必须结束语句,例如"终点;",'endif;'等等在同一组PHP标签中。

如果您只有相关语句中的PHP(如果,等等),则可能将所有内容都放在一组PHP标签中,而不是例如"最终";和" endif;"语句位于单独的集合中。在这种情况下,您的代码不包含HTML或任何标记,因此也可以将其全部写入一组PHP标签中:

<?php       
    $lastBlog = new WP_Query('type=post&posts_per_page=1&category_name=news');
    if ( $lastBlog->have_posts() ) {
        while( $lastBlog->have_posts() ) {
            $lastBlog->the_post(); 
            // Added 'echo' to output the content
            echo get_template_part('content/content',get_post_format()); 
        } // End of 'while' statement
    } // End of 'if' statement
    wp_reset_postdata();
?>

尽管您的代码的当前状态可以像这样编写,但它的方式很好,并且您允许您明确添加HTML的当前结构,例如:

<?php       
    $lastBlog = new WP_Query('type=post&posts_per_page=1&category_name=news');
    if ( $lastBlog->have_posts() ):
        while( $lastBlog->have_posts() ): $lastBlog->the_post(); 
?>
<?php get_template_part('content/content',get_post_format()); ?>
<p>HTML EXAMPLE - THIS WOULD APPEAR FOR EACH POST IN THE WHILE LOOP</p>
<?php 
        endwhile;
    endif;                  
    wp_reset_postdata();
?>

上面的示例只是表明在代码中不同的PHP代码块中明确使HTML明确的。我知道您的代码中的" get_template_part"调用实际上是HTML输出的原因。

总的来说,您的代码和语句都很好。如果您确实移动了"最终";和" endif;"对您的逻辑心态告诉您的语句,这意味着" get_template_part"调用将不在'if'和'while'语句之外。虽然这可能不会更改您的页面当前工作方式(因为您只输出一个帖子),但如果您决定要输出更多帖子,则代码无法正常工作,因为'get_template_part'方法只会被调用一次(而不是一次)对于每个帖子),因为它在" while"循环之外。将您的代码按原样构造,如果您更改了WP_QUERY,则应用于输出一个或许多帖子。

希望这会有所帮助!

最新更新