【问题标题】:Get categories with posts that contain certain tag获取包含特定标签的帖子的类别
【发布时间】:2016-04-30 00:38:02
【问题描述】:

我们有 10 个类别,比如 A、B、C、D 等

我们有 1 个标签,比如 tag

函数get_categories 将获取所有包含帖子的类别(默认情况下),但我们需要的是相同的函数,只是我们只需要获取具有特定标签的帖子的类别。

所以类别A 有5 个带有标签tag 的帖子,类别B 没有,类别C 有3 个。然后我想在这个列表中看到AC

是否可以按标签过滤get_categories

更新 1

试过

$terms = get_terms( array(
            'taxonomy' => 'category',
            'hide_empty' => true,
            'meta_query' => array(
                array(
                    'key'     => 'tag',
                    'value'   => 'my-tag-slug',
                    'compare' => '=',
                ),
            ),
        ) );

也尝试使用标签 ID。这是我使用的标准帖子类别和标签。

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    改用 get_terms() 并使用您可以使用的 meta_query 参数:https://developer.wordpress.org/reference/functions/get_terms/

    类似:

    $terms = get_terms( array(
        'taxonomy' => 'category',
        'hide_empty' => true,
        'meta_query' => array(
            array(
                'key'     => 'tag',
                'value'   => 'tag',
                'compare' => '=',
            ),
        ),
    ) );
    

    这取决于您使用的 WordPress 版本 - 请查看文档。

    查看https://codex.wordpress.org/Class_Reference/WP_Query 以了解有关参数的“元查询”部分的更多信息。

    更新

    尝试这样的事情(注意将 {tag-slug} 更改为您所需的标签 slug

    // Get the categories
    $terms = get_terms( array(
        'taxonomy' => 'category',
    ) );
    
    // Loop through them
    foreach($terms as $term) {
      // Get the posts in that category with the required tag
      $args = array(
        'category_name'    => $term->name,
        'tax_query'      => array(
            array(
                'taxonomy'  => 'post_tag',
                'field'     => 'slug',
                'terms'     => '{tag-slug}'
            )
        )
      );
      $posts_array = get_posts( $args );
    
      foreach ($posts_array as $value) {
        // save what you need here - maybe an array for each category with the posts so you can run a count on them?
      }
    
    }
    

    【讨论】:

    • 谢谢,我试过了,但似乎不起作用。我得到一个空数组。我在 4.5.1,所以你的代码很好。我也找不到与 codex.wordpress.org/Class_Reference/WP_Meta_Query 或 Google 上的标签相关的任何内容...
    • 您能否展示您的代码版本 - 这样我就可以看到您的类别和元名称是什么。如果您只是按原样复制和粘贴,我的示例将不起作用。
    • 啊,你在我打字的时候更新了——所以你有一个叫做“tag”的元字段,你在这个叫做“my-tag-slug”的下面添加了一个值,对吗?您只是使用默认的 WordPress 类别和标签吗?
    • 不,不是元字段。我们正在使用 Wordpress 的实际 tag 系统
    • 更新了我的答案 - 需要一些工作,但应该让你朝着正确的方向前进
    猜你喜欢
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    相关资源
    最近更新 更多