[英]WordPress: Get terms from author
在作者存档页面上,我想显示作者发布帖子(在我的情况下为 WooCommerce 产品)的每个分类法(在我的情况下为产品类别)。
为此,我使用以下代码:
$posts = get_posts( array('post_type' => 'product', 'posts_per_page' => -1, 'author' => $author_id) );
$author_categories = array();
//loop over the posts and collect the terms
foreach ($posts as $p) {
$author_categories = wp_get_object_terms( $p->ID, 'product_cat');
if ( ! empty( $author_categories ) && ! is_wp_error( $author_categories ) ){
echo '<div class="d-flex flex-wrap">';
foreach ($author_categories as $author_category) {
//var_dump($t);
$author_category_link = get_term_link( $author_category );
$author_category_name = $author_categories[] = $author_category->name;
echo '<a href="'.esc_url( $author_category_link ).'" class="p-2 p-lg-5 bg-light text-center">';
echo $author_category_name;
echo '</a>';
}
echo '</div>';
}
}
wp_reset_postdata();
问题是,产品类别出现多次。 我想对于该产品类别中的每个帖子。
有没有办法先收集术语并仅按产品类别中的帖子数排序一次才显示它们?
您应该首先收集容器数组中的所有类别。 通过在将类别添加到数组时使用类别的 ID 或名称作为数组键,可以消除重复项。 然后,您只需遍历结果数组即可回显类别。
// First just collect the distinct categories.
$posts = get_posts( array('post_type' => 'product', 'posts_per_page' => -1, 'author' => $author_id) );
$all_author_categories = array();
foreach ($posts as $p) {
$author_categories_for_p = wp_get_object_terms( $p->ID, 'product_cat');
if ( ! empty( $author_categories_for_p ) && ! is_wp_error( $author_categories_for_p ) ){
foreach ($author_categories_for_p as $author_category) {
$all_author_categories[$author_category->name] = $author_category;
}
}
}
// Then just loop over the collected categories and display them.
echo '<div class="d-flex flex-wrap">';
foreach($all_author_categories as $author_category) {
$author_category_link = get_term_link( $author_category );
$author_category_name = $author_categories[] = $author_category->name;
echo '<a href="'.esc_url( $author_category_link ).'" class="p-2 p-lg-5 bg-light text-center">';
echo $author_category_name;
echo '</a>';
}
echo '</div>';
评论:
wp_reset_postdata();
最后不需要,因为您没有更改全局$post
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.