[英]Get Custom Custom Taxonomy Terms with a Count of Duplicates
我有一個帶有自定義分類法的自定義帖子類型的自定義wordpress查詢。 我正在嘗試回顯鏈接的術語(標簽)列表。 對於重復的字詞,我想顯示重復字詞的數量。 不幸的是,在調用array_unique()之前,我不知道如何計算項目和存儲信息。 任何建議將不勝感激。 這是我的Wordpress查詢:
//Begin Custom Query
$args=array(
'post_type' => 'gw_activity',
'post_status' => 'publish',
'orderby' => 'date',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'activity_category',
'value' => 'mindful_life',
'compare' => '='
)
),
'posts_per_page' => -1
);
$my_query = null;
$my_query = new WP_Query($args);
這是我建立術語數組的方式:
if( $my_query->have_posts() ) {
$all_terms = array();
$all_slugs = array();
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php $terms = wp_get_post_terms( $my_query->post->ID, array( 'gw_activity_tag' ) ); ?>
<?php
foreach ( $terms as $term ) {
$all_terms[] = $term->name; // Used for Display Purposes
$all_slugs[] = $term->slug; // Used in the Final Permalink of the term
}
?>
<?php endwhile; }
wp_reset_query();
// End Custom Query
這是我制作術語和子詞獨特數組的方式:
$unique_terms = array_unique( $all_terms ); // Eliminate Duplicate Terms
$unique_slugs = array_unique( $all_slugs ); // Eliminate Duplicate Slugs
$final_term_list = array(); //Build Array of Unique Terms
$i = 0;
foreach ($unique_terms as $value) { // Build a Unique Array of Terms
$final_term_list[$i] = $value;
$i++;
}
$final_slug_list = array(); //Build Array of Unique Slugs
$s = 0;
foreach ($unique_slugs as $slug_value) { // Build a Unique Array of Slugs
$final_slug_list[$s] = $slug_value;
$s++;
}
這是我輸出數據的方式
$fl = 0; //Create a counter to index the array
foreach($final_slug_list as $final_slug) {
echo '<a href="'. get_bloginfo('url') .'/activity-category/'. $final_slug_list[$fl] .'/">'.$final_term_list[$fl].'</a>';
$fl++;
} // End foreach
您可以嘗試以下方法...
$count_terms = array_count_values($all_terms);
$count_slugs = array_count_values($all_slugs);
您可以這樣做,但要短一些。
$all_terms = array();
$all_slugs = array();
foreach ( $myMapPosts as $post ) : setup_postdata( $post );
$terms = wp_get_post_terms( $post->ID, array( 'listing_category' ) );
foreach ( $terms as $term ) {
$all_terms[$term->slug] = array('name' => $term->name, 'slug' => $term->slug, 'count'=>0); // Used for Display Purposes
$all_slugs[] = $term->slug;
}
endforeach;
$terms = array_count_values($all_slugs);
foreach ($terms as $key => $value) {
$all_terms[$key]['count'] = $value;
}
var_dump($all_terms);
這樣,您不必擔心刪除重復項
結果
array(3) {
["restaurants-cafes"]=>
array(3) {
["name"]=>
string(23) "Restaurants & Cafes"
["slug"]=>
string(17) "restaurants-cafes"
["count"]=>
int(20)
}
["food-stores-markets"]=>
array(3) {
["name"]=>
string(25) "Food Stores & Markets"
["slug"]=>
string(19) "food-stores-markets"
["count"]=>
int(8)
}
["other"]=>
array(3) {
["name"]=>
string(5) "Other"
["slug"]=>
string(5) "other"
["count"]=>
int(2)
}
}
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.