首页 > 解决方案 > 你可以在 WordPress 循环中有 2 个相邻的“if”语句吗?什么是最佳实践?

问题描述

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

第一个代码片段完美运行并显示了我想要的所有内容,但它是编写它的最佳方式吗?我可以使用 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>

标签: wordpressloopsif-statementconditional-statementswordpress-theming

解决方案


编辑 1.2:

我可以使用 2 if 语句彼此相邻还是这是不好的做法?

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

在您的情况下,您正在谈论两个不同的循环,一个用于帖子一个用于标签,两个 if 语句都不相关。您正在帖子循环内运行标签循环。

最佳实践是每次都有一个后备

<?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()
@ https://developer.wordpress.org/reference/functions/the_tags/the_tags()


推荐阅读