Php 获取相对于当前查询的类别计数

Php 获取相对于当前查询的类别计数,php,wordpress,Php,Wordpress,我正在使用WordPress,在搜索页面上,我需要获取类别内的帖子数量,并将其显示在名称旁边。像这样 第1类(3) 第2类(1) 第3类(18) 目前,我正在使用get_categories()函数,该函数为您提供一个对象,并使用$cat->count()获取计数。这将获取术语中的帖子总数,但我只需要从当前查询中的帖子中获取该计数。我正在使用pre\u get\u posts更新查询。有人知道这样做的方法吗 这是我当前的代码块 foreach ( get_categories() as $ca

我正在使用WordPress,在搜索页面上,我需要获取类别内的帖子数量,并将其显示在名称旁边。像这样

第1类(3) 第2类(1) 第3类(18)

目前,我正在使用
get_categories()
函数,该函数为您提供一个对象,并使用
$cat->count()
获取计数。这将获取术语中的帖子总数,但我只需要从当前查询中的帖子中获取该计数。我正在使用
pre\u get\u posts
更新查询。有人知道这样做的方法吗

这是我当前的代码块

foreach ( get_categories() as $cat ) {
    if ( $cat->parent === 0 ) {
        $checked = ( in_array( $cat->slug, $check ) ) ? 'checked' : '';

        printf( '<input id="%1$s" %4$s type="checkbox" name="category[%1$s]"><label for="%1$s" >%2$s ( %3$d )</label><br>',
            $cat->slug,
            $cat->name,
            $cat->count,
            $checked
        );
    }
}

这是一个有趣的问题。不幸的是,您无法使用
get_categories
,因此您需要另一种方法

以下是我们将如何做到这一点:

  • 创建一个非常精简的自定义查询,从与查询匹配的所有帖子中获取所有帖子ID

  • 将所有类别附加到帖子

  • 循环浏览所有帖子和帖子中的类别,并构建一个以类别名称为键、以帖子ID为值的数组

  • 循环浏览这个新数组,并显示类别名称,同时计算并显示该特定键(类别)的帖子数量

守则: (注意:由于新的数组语法(
[]
),以下代码未经测试,需要在leat PHP5.4+上使用)

$cats=(isset($\u GET['category']))?内爆(“,”,数组_键($\u GET['category']):null;
$search=(isset($\u GET['s'])?清理文本字段($\u GET['s']):空;
$args=[
“post_type”=>“post”,
'nopaging'=>true,//获取所有帖子
's'=>$search,
“类别名称”=>$cats,
'fields'=>'ids',//使查询非常精简,性能优异,仅获取帖子ID
];
$q=获取帖子($args);
//定义我们的$category_数组,它将保存类别名称/帖子ID的数组
$category_数组=[];
//定义$category_info数组,该数组将类别名称作为键,对象作为值
$category_info=[];
foreach($q作为$post){
//获取附加到帖子的类别
$categories=获取类别($post);
foreach($categories作为$category){
//创建我们的数组,它将类别名称作为键,将post ID作为值
$category_数组[$category->name][]=$post;
//创建一个数组来保存类别对象。使用名称作为键,对象作为值
$category\u info[$category->name]=$category;
}//endforeach$categories
}//endforeach$wp_query->posts
wp_reset_postdata();
//按字母顺序对数组键排序。您可以根据需要更改或删除此项
ksort($category_数组);
foreach($k=>v的类别数组){
$category\u slug=$category\u info[$k]>slug;
$category\u parent=$category\u info[$k]->parent;
$checked=(在_数组($category_slug,$check))中?'checked':“”;//只需确保在某个地方定义了$check
//建立我们的关系
printf(“%2$s(%3$d)
”,//我没有修改此行中的任何内容 $category\u slug,//保存类别slug $k,//保存类别名称 count($v),//计数并返回post计数 美元支票 ); }//endforeach$category\u数组
嘿,彼得,我刚刚看到了这个答案。谢谢你花时间写出来。这让我走上了正确的道路。我和伯爵还有点意见。如果I
var\u dump($v)我得到的数字1重复有多少职位是该类别。计数仅显示1,因此类别看起来是这样的:类别1(1),而实际上有更多的类别。知道如何存储每个变量的计数吗?ThanksI已经更新了答案,它现在正在工作,唯一的问题是,如果查询分页,计数是错误的。我将需要运行一个自定义查询,以获得所有的职位运行计数正确。我将添加一个通用的解决方案Done,查询现在应该可以工作了。请注意,我已经删除了家长支票。如果需要,请告诉我,以便我可以将其添加回;-)令人惊叹的!非常感谢你。在您使用
get\u posts()
编辑您的帖子之前,我已经开始工作了。我真的很感谢你的帮助!我的荣幸。只需确保在代码中添加
字段
参数,否则查询会非常繁重;-)我的答案行不通,我需要做一些调整。不幸的是,我现在不能这样做。稍后我们将对此进行研究。会让你了解最新情况。同时,添加过滤搜索查询的
pre\u get\u posts
操作,这对我的回答非常重要,我完全理解。谢谢你的意见。我正忙着整理一切。只是等待你的
pre\u get\u posts
action刚刚更新了我的问题。谢谢您的帮助。好的,我现在将合并它以修复计数;-)
add_action( 'pre_get_posts', 'breed_search_query' );
function breed_search_query( $query ) {
$cats   = ( isset( $_GET['category'] ) ) ? implode( ',', array_keys( $_GET['category'] ) ) : null;
$search = ( isset( $_GET['s'] ) ) ? sanitize_text_field( $_GET['s'] ) : null;

    if ( ! is_admin() && $query->is_main_query() && is_search() ) {
        $query->set( 'post_type', 'post' );
        $query->set( 'posts_per_page', 8 );
        $query->set( 's', $search );
        $query->set( 'category_name', $cats );
    }
}
$cats   = ( isset( $_GET['category'] ) ) ? implode( ',', array_keys( $_GET['category'] ) ) : null;
$search = ( isset( $_GET['s'] ) ) ? sanitize_text_field( $_GET['s'] ) : null;

$args = [
    'post_type'     => 'post',
    'nopaging'      => true, // Gets all posts
    's'             => $search,
    'category_name' => $cats,
    'fields'        => 'ids', // Makes the query extremely lean, excellent for performance, only get post ID's
];
$q = get_posts( $args );

// Define our $category_array which will hold the category name/post ID's array
$category_array = [];

// Define our $category_info array which will hold the category name as key and the object as value
$category_info = [];

foreach ( $q as $post ) {
    // Get the categories attached to a post
    $categories = get_the_category( $post );

    foreach ( $categories as $category ) {
        // Create our array which will hold the category name as key and post ID's as values
        $category_array[$category->name][] = $post;
        // Create an array to hold the category objects. Use names as keys and objects as values
        $category_info[$category->name] = $category;
    } // endforeach $categories
} // endforeach $wp_query->posts
wp_reset_postdata();

// Sort the array keys alphabetical. You can change or remove this as necessary
ksort( $category_array );

foreach ( $category_array as $k=>$v ) {

    $category_slug = $category_info[$k]->slug;
    $category_parent = $category_info[$k]->parent;

    $checked = ( in_array( $category_slug, $check ) ) ? 'checked' : ''; // Just make sure that $check is defined somewhere

    // Build our string
    printf ( '<input id="%1$s" %4$s type="checkbox" name="category[%1$s]"><label for="%1$s" >%2$s ( %3$d )</label><br>', // I have not modified anything in this line
        $category_slug, // Holds the category slug
        $k, // Holds the category name
        count( $v ), // Counts and return the post count
        $checked
    );
} // endforeach $category_array