什么是最好的方法,只显示一个分类的名称一次?我使用了一个名为show_category的分类法,它有三个类别:新闻、评论和未分类。我有六篇文章:新闻三篇,评论一篇,未分类的两篇。它们显示如下:
News (name of category in taxonomy) News item 1 News (name of category in taxonomy) News item 2 News (name of category in taxonomy) News item 3 Reviews (name of category in taxonomy) Review item Uncategorized (name of category in taxonomy) tes Uncategorized (name of category in taxonomy) test 2
我正在寻找一种方法,在分类法中只使用一次这样的类别名称:
News (name of category in taxonomy) News item 1 News item 2 News item 3 Reviews (name of category in taxonomy) Review item Uncategorized (name of category in taxonomy) Tes Test 2
我的循环代码:
name;
endforeach;?>
>发布于 2019-10-01 21:59:16
不是最好的,但对我来说效果很好:(你可以用这个代替问题中的内容)
$postcount = 0;
//global $wp_query; // Uncomment if necessary.
// Group the posts by category.
$groups = [];
foreach ( $wp_query->posts as $i => $p ) {
$terms = wp_get_post_terms( $p->ID, 'show_category' );
foreach ( $terms as $t ) {
if ( ! isset( $groups[ $t->term_id ] ) ) {
$groups[ $t->term_id ] = [];
}
$groups[ $t->term_id ][] =& $wp_query->posts[ $i ];
}
}
// And display the posts under their own category. Note though, that a post may
// appear twice if it's assigned to multiple categories.
global $post;
foreach ( $groups as $term_id => $posts ) {
$term = get_term( $term_id );
// Display the term/category name.
echo '' . esc_html( $term->name ) . '';
// And the category's posts.
foreach ( $posts as $post ) {
setup_postdata( $post );
?>
>PS:h3标签只是一些例子。
https://wordpress.stackexchange.com/questions/349530
复制相似问题