【问题标题】:Wordpress posts count with comman tags within specific categoryWordpress 帖子使用特定类别中的命令标签计数
【发布时间】:2018-06-07 14:13:18
【问题描述】:

我有两个类别“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

【问题讨论】:

    标签: php sql wordpress


    【解决方案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);
    

    我没有测试过这段代码,但它应该可以工作。你当然有 设置正确的条款。


    更新

    在处理许多帖子时,我会创建一个 $wpdb sql 查询来计算行数,因此只返回一个数字而不是所有帖子。您可以找到一个 sql 计数示例here

    【讨论】:

    • 谢谢,但它会增加 CPU 负载。我有大约 100000 个帖子。
    • 这是最快的,因为它是单个查询。 100k 个帖子很多,但我认为它会足够快,当然这也取决于您运行它的服务器。
    • Bjorn,无论如何我不确定这是最好的解决方案。试想一下,您的服务器需要多少内存来保存一个包含大约 20-30,000 个帖子的数组...
    【解决方案2】:

    您可以使用 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2018-06-24
      相关资源
      最近更新 更多