Is it possible to calculate the percentage of posts in each given category? I’d like to make a bar chart to visualize the amout of posts in those categories.
I thought what one needs would be the total amount of posts, the amount of posts in each category and then a PHP function that calculates percentages with those values and applies a variable to it which I need to use when building the bar chart.
I am not very familiar with extended PHP, so if anyone could show me the right direction, I’d be grateful
With a little CSS, this will create a list of categories like so:
![enter image description here](https://i.stack.imgur.com/RFI5U.png)
Basic CSS:
<style>
.bar { height:4px; background:blue; }
</style>
The PHP:
<?php
// To customize visit http://codex.wordpress.org/Function_Reference/get_categories
$categories = get_categories();
// Get total posts, this allows for posts to have more than one category and accommodates for custom $args in get_categories($args)
$total_posts = 0;
foreach ($categories as $category) {
$total_posts += $category->count;
}
// Loop through the categories
$total_check = 0;
foreach ($categories as $category) {
// Get the % and round to 2 decimal places
$percentage = round( (($category->count / $total_posts)*100), 2 );
// Just checking to see if they will add up to 100 at the end
$total_check += $percentage;
echo '
<div class="category-wrap">
<h3>'.$category->cat_name.'</h3>
<div class="bar" style="width:'.$percentage.'%;"></div>
</div><!-- .category-wrap -->
';
}
// Just checking to see that they all add up to 100, delete or comment out afterward
echo $total_check;
?>