您可以在 WordPress 循环中将 2 个 "if" 语句并排放置吗?什么是最佳实践?

Can you have 2 "if" statements next to each other within the WordPress Loop? What is best practice?

我正在尝试为 WordPress 博客创建 single.php post 页面。我已经使用 Loop 来浏览实际内容,但也想显示标签(如果有的话)!

第一个代码片段完美运行并显示了我想要的所有内容,但这是最好的编写方式吗? 我可以并排使用 2 个 if 语句吗?这是一种不好的做法吗?我已经尝试了两种方法:2 个 IF 语句有效,但 1 个 IF 语句无效...见下文!

提前致谢!

工作代码片段(使用 2 个 IF 语句)

<?php get_header();?>

<div class="blog-content row">
    <div class="col">
    
    <?php if(have_posts()) : while(have_posts()) : the_post();?>

        <p class="single-date"><?php echo get_the_date();?></p>
        <?php the_content();?>
    
    <?php endwhile; else: endif;?>

    <?php
      $tags = get_the_tags();
      if( $tags ) :
         foreach( $tags as $tag ) : ?>
            <div class="single-tag">
               <a href="<?php echo get_tag_link( $tag->term_id);?>">
                        <?php echo $tag->name;?></a>
            </div>
      
   
      <?php endforeach; endif;?>
      
  
    </div>
</div>

无效代码段(尝试仅使用 1 个 IF 语句)

在这里,我收到以下警告:为 foreach() 提供的参数无效

<?php get_header();?>

<div class="blog-content row">
    <div class="col">
    
    <?php if(have_posts()) : while(have_posts()) : the_post();?>

        <p class="single-date"><?php echo get_the_date();?></p>
        <?php the_content();?>

    <?php endwhile;?>

        <?php $tags = get_the_tags();
          foreach( $tags as $tag ) : ?>
            <div class="single-tag">
               <a href="<?php echo get_tag_link( $tag->term_id);?>">
                        <?php echo $tag->name;?></a>
            </div>
   
          <?php endforeach; endif; ?> 
      
  
    </div>
</div>

<div class="comments-sec">

  <h4>Comments</h4>
  <?php comments_template();?>

</div>

编辑 1.2:

Can I use 2 if statements next to each other or is this bad practice?

是的,你可以,但在你的情况下你不能...在调用 post 之后传递标签。 您需要一个 post 来检查 post 是否有标签。

在你的例子中,你说的是两个不同的循环,一个用于 posts一个用于标签, 两个 if 语句不相关。您是 运行 标签循环 posts.

循环中的标签循环

最佳做法是每次都有后备

<?php 
//START Posts loop
if ( have_posts() ):
while ( have_posts() ):
the_post();
//IF posts exist
echo the_title().'<br/>'.the_content();

//START Tags loop
if( has_tag() ) {
//IF tags exist
echo the_tags();
} else {
//IF no tags exist, then fallbak
echo 'No tags yet!';
};
//END Tags loop

endwhile; else:
//IF no posts exist, then fallbak
echo 'No posts yet!';
endif; 
//END Posts loop
?>

此外,您还可以使用 has_tag()the_tags()
更多@https://developer.wordpress.org/reference/functions/has_tag/ has_tag()
the_tags()

更多@https://developer.wordpress.org/reference/functions/the_tags/