Wordpress帖子计入特定类别中的comman标记

时间:2018-06-07 14:13:18

标签: php sql wordpress

我有两个类别'A'和'B'。两者都有5个帖子(每个)带有标签'C'。如何在“A”或“B”类页面中将帖子数量显示为5。它显示标签'C'的帖子总数为10.我需要将其显示为5.如何通过类别变量来显示特定类别中标签的精确计数。这是我目前的代码:

$tag = get_term_by('name', $tags,'post_tag');
$count = $tag->count;

参考:https://codex.wordpress.org/Function_Reference/get_term_by

2 个答案:

答案 0 :(得分:1)

使用get_term_by()方法无法做到这一点。

试试这个:

$args = array(
  'posts_per_page' => -1,
  'tax_query' => array(
    'relation' => 'AND', // only posts that have both taxonomies will return.
    array(
      'taxonomy' => 'post_tag',
      'field'    => 'name',
      'terms'    => 'TAG_C', // you can also use an array with tags.
    ),
    array(
      'taxonomy' => 'category',
      'field'    => 'slug',
      'terms'    => 'CATEGORY_B', // you can also use an array with categories.
    ),
  ),
);
$posts = get_posts($args);
$count = count($posts);

注意:我没有测试过这段代码,但它应该有效。当然,你必须设置正确的术语。

问候,Bjorn

答案 1 :(得分:0)

您可以使用WP_Query类对象的“ found_posts”属性。

$args = array(
    'posts_per_page'  => 10,
    'category_name'   => 'aaa', // category slug
    'tag'             => 'ccc'  // tag slug
);
$wp_query = new WP_Query( $args );
echo "Total posts count: ".$wp_query->found_posts;