由于您没有提供任何代码,我尝试了我的方式。我想,这不是实现它的最佳方式 但到目前为止,您可以这样做。
在这里,我使用PHP 来实现您想要的结果。
我用过二十四主题的search.php。
这是我的代码,用于二十四岁主题的search.php,您可以在您的search file 中实现:
<?php
/**
* The template for displaying Search Results pages
*
* @package WordPress
* @subpackage Twenty_Fourteen
* @since Twenty Fourteen 1.0
*/
get_header(); ?>
<section id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyfourteen' ), get_search_query() ); ?></h1>
</header><!-- .page-header -->
<?php
// Start the Loop.
$post_id_array = array(); //Blank array to store all Post IDs
while ( have_posts() ) : the_post();
array_push($post_id_array, $post->ID); //store ID to array
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
endwhile;
// Previous/next post navigation.
twentyfourteen_paging_nav();
$catarray = array(); //Blank array to store all categories
$k=1;
foreach($post_id_array as $my_post){
$my_category = get_the_category( $my_post );
foreach($my_category as $my_cat){
array_push($catarray, $my_cat->cat_name); //Store category in array
}
$something = array_count_values($catarray); //Count total number of element in category array
foreach(array_unique($catarray) as $some){
if($k == sizeof($my_category) ): //Condition to print all thing if only it is last element of an array.
echo $some."(". $something[$some].")<br>";
endif;
}
$k++;
}
else :
// If no content, include the "No posts found" template.
get_template_part( 'content', 'none' );
endif;
?>
</div><!-- #content -->
</section><!-- #primary -->
<?php
get_sidebar( 'content' );
get_sidebar();
get_footer();
在上面的代码中,我已经完成了:
第 1 步:使用一个空白数组来存储搜索查询给出的帖子ID。
Step-2 : 使用 PHP 的 array_push 函数将所有 ID 推入创建的 空白数组。 注意:确保您已将其放入while loop 以获取所有ID。
两步之后,现在您有了一个所有帖子 ID 的数组。
Step-3:取另一个空白数组来存储帖子的相关类别名称。
Step-4 :取一个变量并将其值赋予1,这在最后很有用。(我已经采取$k = 1)。
第 5 步:制作一个foreach 帖子 ID 循环。并获取带有wordpress功能的帖子的类别名称get_the_category.It will fetch category based on post ID。
第 6 步:现在是时候使用我们为类别名称创建的空白数组了。所以只需loop类别名称和 store 类别名称到 array 中。
Step-7:计数类别数组中的总名称,使用 PHP 的 array_count_values 函数并为其分配变量。(我使用了 $something)。
在step-7之后,我们有一个类别名称数组。 注意:在此数组中,类别名称可能存在重复。要删除重复,请执行下一步。
Step-8:使用 PHP 的 'array_unique' 函数从数组中仅获取 唯一值。
第 9 步:创建一个类别名称的loop。
如果你现在echo,it will print categories to total number of post times。
所以现在是时候使用我们在foreach 循环帖子 ID($k=1) 之前获取的变量了。
最后一步:现在一个条件在最后一个帖子打印所有类别。
因此,我使用了if($k == sizeof($my_category) ),这意味着,它只会在类别数组的长度等于变量K时打印(简而言之,最后)。
增加$k的值。
希望对您有所帮助。如果您有任何疑问,请咨询我。