简体   繁体   English

如何按ID显示标签中的帖子数?

[英]How to display number of posts from a tag by id?

Trying

<?php
$number = 'apartamenty';

$terms = get_terms('post_tag', "number=$number");
if($terms){
foreach ($terms as $t){
    echo $t->name.' : '.$t->count;
}
}?>

But this code show two tags... 但是这段代码显示了两个标签...

To get the number of posts that are attached to a specific post tag, such as apartamenty , you would use get_term_by() . 要获取附加到特定帖子标签(例如apartamenty帖子apartamenty ,可以使用get_term_by() This WordPress Core construct lets you grab the WP_Term object for the specific post tag. 此WordPress Core构造可让您获取特定post标记的WP_Term对象。 In your case, you are wanting the post tag of apartamenty . 在您的情况下,您需要apartamenty的post标签。

Okay, you'd have a function (ie to make it reusable) that runs this code and you'd pass in the actual post tag that you want to explore. 好的,您将有一个运行该代码的函数(即使其可重用),然后传递您想要探索的实际post标签。 This function is using the post tag slug. 此功能正在使用post标签。

function render_post_tag_post_count( $post_tag ) {
    $term = get_term_by( 'slug', $post_tag, 'post_tag' );
    if ( ! $term ) {
        return;
    }

    // You get back an WP_Term object
    // You can then use $term->count, which gives you the
    // number of posts attached to this post tag.

    echo (int) $term->count;
}

The property $term->count gives you the number of posts that are attached to that term. $term->count属性可为您提供该术语的附加帖子数。

You use it like this: 您可以这样使用它:

render_post_tag_post_count( 'apartamenty' );

What if I want to get it by post tag ID? 如果我想通过邮政标签ID获得该怎么办?

Take the above code and change the first argument from slug to id . 使用上面的代码,并将第一个参数从slug更改为id Then you would pass the post tag's ID instead of its slug. 然后,您将传递帖子标签的ID而不是它的标签。

You can learn more about the parameters in WordPress Codex . 您可以了解有关WordPress Codex中参数的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM