我正在为WordPress中的类别和标记存档页面编辑主题模板,并且已经使用以下方法成功地打印了这个类别。
<div class='avia-section-search'>
<div class='container'>
<?php
echo "<h2 class='entry-content-wrapper'>Level: ";
global $post;
$postcat = get_the_category( $post->ID );
if ( ! empty( $postcat ) ) {
foreach ($postcat as $nameCategory) {
echo $nameCategory->name .' ';
}
}
"</h2>";
?>
</div>
</div>我已经调整了标签的代码,但是它打印了所有的标签
global $post;
$posttags = get_the_tags( $post->ID );
if ( ! empty( $posttags ) ) {
foreach ($posttags as $nameTags) {
echo $nameTags->name .' ';
}
}理想情况下,我只需要打印用户选择的当前标签。
任何帮助都将不胜感激。
谢谢理查德
发布于 2020-09-10 19:42:09
正如您所看到的,WP函数返回帖子上的所有标记,因为它们不知道要得到哪个标签。我们需要做的是获取用于显示帖子的标记。
有两种方法可以做到这一点:
默认情况下,这将将标签的标题回显到屏幕上,例如:
<h1><?php single_tag_title(); ?></h1>...or,您可以将false作为第二个参数传入,以防止输出,以便将其保存为变量。
<?php $title = single_tag_title('', false); ?>2.获取标记的所有详细信息:
存档页面(就像您正在使用的那样,或者如果使用的话是另一个页面)将执行一个使用所选标记的段塞的查询。这意味着我们可以得到被查询的对象。
在本例中,我们得到了一个WP_Term object,它包含术语信息查询的细节,如段塞、标记id等:
$page_tag = get_queried_object();
// now you can do whatever you want with the tag, e.g.
$tag_name = $page_tag->name;
$tag_slug = $page_tag->slug;
$tag_id = $page_tag->term_id;
$tag_parent = $page_tag->parent; UPDATE:使用您自己添加到问题中的代码:
1. single_tag_title()
<div class='avia-section-search'>
<div class='container'>
<h2 class='entry-content-wrapper'><?php single_tag_title(); ?></h2>
</div>
</div>2. get_queried_object()
<div class='avia-section-search'>
<div class='container'>
<h2 class='entry-content-wrapper'>
<?php
$page_tag = get_queried_object();
echo $page_tag->name; // echo the tag name
?>
</h2>
</div>
</div>https://stackoverflow.com/questions/63815596
复制相似问题