本质上,您需要的是显示当前查询的帖子所属的类别。我将在这里发布一个函数,该函数以taaxonomy(或一组分类法)作为参数,并返回该分类法中分配给所有查询帖子的所有术语。
function queried_posts_terms( $taxonomies = \'category\' ) {
global $wp_query, $wpdb;
if ( empty( $wp_query->posts ) ) return FALSE;
$ids = wp_list_pluck( $wp_query->posts, \'ID\' );
$taxonomies = array_filter( (array) $taxonomies, function( $tax ) {
if ( is_string( $tax ) ) {
$tax = sanitize_title( $tax );
return taxonomy_exists( $tax ) ? esc_sql( $tax ) : NULL;
}
} );
if ( empty( $taxonomies ) ) return FALSE;
$sql = "SELECT t.name, t.slug, t.term_group, tt.*
FROM {$wpdb->terms} t
INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
INNER JOIN {$wpdb->term_relationships} tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tr.object_id IN (" . implode( \', \', $ids ) . ")
AND tt.taxonomy IN (\'" . implode( "\', \'", $taxonomies ) . "\')
GROUP BY t.term_id";
return $wpdb->get_results( $sql );
}
一旦在
functions.php
(或在活动插件中)在模板中
search.php
只需使用:
if ( is_search() ) {
$cats = queried_posts_terms( \'category\' );
echo ! empty( $cats ) ? \'<ul>\' : \'\';
foreach( $cats as $cat ) {
printf( \'<li><a href="%s">%s</a></li>\', get_term_link($cat), esc_html($cat->name) );
}
echo ! empty( $cats ) ? \'</ul>\' : \'\';
}