按类别计算帖子百分比

时间:2014-07-16 作者:okiedokey

是否有可能计算每个特定类别的员额百分比?我想做一个条形图来直观显示这些类别中的帖子数量。

我想我们需要的是帖子的总量,每个类别中的帖子数量,然后是一个PHP函数,该函数使用这些值计算百分比,并对其应用一个变量,我需要在构建条形图时使用该变量。

我对扩展PHP不是很熟悉,所以如果有人能告诉我正确的方向,我将不胜感激

2 个回复
最合适的回答,由SO网友:deflime 整理而成

通过一点CSS,这将创建一个类别列表,如下所示:

enter image description here

基本CSS:

<style>
  .bar { height:4px; background:blue; }
</style>
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;
?>

SO网友:Eric Allen

根据您想在何处使用它,您可以找到不同的方法来处理它,但我提供了一个简单函数的代码,您可以将其放入函数中。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();

然后可以遍历该数组,并对其执行所需的操作。生成条形图的方法有很多,因此此答案侧重于问题的标题,并且与所需的图形方法无关。

结束