根据您想在何处使用它,您可以找到不同的方法来处理它,但我提供了一个简单函数的代码,您可以将其放入函数中。php并调用主题中的任意位置以获取百分比数组。
此方法结合使用wp_count_posts()
和get_categories()
.
当您将小数转换为百分比时,可能需要进行一些舍入。我省略了这一点,以便您可以决定如何处理这些数字。
//function to return array of percentage of posts in each category
function wpse_154771() {
//get # of posts of each status
$total = wp_count_posts();
//# of published posts
$total_posts = $total->publish;
$args = array();
//if you want to include categories with no posts uncomment the line below
//$args[\'hide_empty\'] = 0;
//get all categories
$categories = get_categories($args);
//array for storing category percentage
$percent_array = array();
//iterate through categories and get percentage of posts
foreach($categories as $cat) {
//get the decimal representation of this percentage, you can convert as needed
$cat_percentage = $cat->count / $total_posts;
//store percentage in array with category slug as array index
$percent_array[$cat->slug] = $cat_percentage;
}
//return our array of percentages
return $percent_array;
}
使用如下功能:
$percentages = wpse_154771();
然后可以遍历该数组,并对其执行所需的操作。生成条形图的方法有很多,因此此答案侧重于问题的标题,并且与所需的图形方法无关。