在WordPress中获取文章的前三个标签,你可以在循环中使用以下代码:
方法一:使用 get_the_tags() 函数
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div class="post-content">
<?php the_excerpt(); ?>
</div>
<div class="post-tags">
<?php
$tags = get_the_tags();
if ($tags) {
$count = 0;
foreach ($tags as $tag) {
if ($count < 3) {
echo '<a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a>';
$count++;
// 如果不是最后一个标签,添加分隔符
if ($count < 3 && $count < count($tags)) {
echo ', ';
}
}
}
}
?>
</div>
</article>
<?php endwhile; endif; ?>
方法二:更简洁的写法
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div class="post-content">
<?php the_excerpt(); ?>
</div>
<div class="post-tags">
<?php
$tags = get_the_tags();
if ($tags) {
$tag_count = 0;
foreach ($tags as $tag) {
if ($tag_count < 3) {
echo '<span class="tag"><a href="' . get_tag_link($tag->term_id) . '">#' . $tag->name . '</a></span>';
$tag_count++;
}
}
}
?>
</div>
</article>
<?php endwhile; endif; ?>
方法三:使用 array_slice() 函数
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div class="post-content">
<?php the_excerpt(); ?>
</div>
<div class="post-tags">
<?php
$tags = get_the_tags();
if ($tags) {
$first_three_tags = array_slice($tags, 0, 3);
foreach ($first_three_tags as $tag) {
echo '<a href="' . get_tag_link($tag->term_id) . '" class="tag-link">' . $tag->name . '</a> ';
}
}
?>
</div>
</article>
<?php endwhile; endif; ?>
本文地址: wordpress调用文章内的三个标签
版权声明:如发现本站有涉嫌抄袭侵权/违法违规的内容请联系客服!




