Calculate percentage of post by category

With a little CSS, this will create a list of categories like so:

enter image description here

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;
?>

Leave a Comment