【发布时间】:2021-01-06 18:51:18
【问题描述】:
我正在尝试为 WordPress 博客创建 single.php 帖子页面。我已经使用循环来提取实际内容,但也想显示标签(如果有的话)!
第一个代码 sn-p 完美运行并显示了我想要的所有内容,但它是最好的编写方式吗? 我可以使用 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>
【问题讨论】:
标签: wordpress loops if-statement conditional-statements wordpress-theming