Wordpress count_posts()等价函数非常昂贵的方法

时间:2014-02-15 14:37:30

标签: php wordpress function count

我希望计算上周的帖子数量,然后通过一个名为“topic”的自定义分类法对它们进行分组。因此,在下一个get_posts等式中,我可以按照最后一个帖子的数量来获取主题周。

可以通过获取帖子这样做,但我担心这在服务器上不必要地昂贵。还有另一种方式吗?

function count_posts_by_taxanomy($since,$taxonomy){
    global $sincer;
    $sincer = $since;

    function filter_post_count($where = ''){
        global $sincer;
        $where .= " AND post_date > '" . date('Y-m-d', strtotime($sincer)) . "'";
        return $where;
    }

    $args = array(
        'numberposts' => -1,
        'post_type' => 'post',
        'suppress_filters' => false
    );

    add_filter('posts_where','filter_post_count');
    $posts = get_posts($args);
    remove_filter('posts_where','filter_post_count');

    $count_term = array();

    foreach($posts as $post){
        foreach(get_the_terms($post->ID,'topic') as $term){
            $count_term[$term->slug] += 1;
        }
    }
    print_r($count_term);

}

这样称呼:

count_posts_by_taxanomy('-5 days','topic');

2 个答案:

答案 0 :(得分:1)

您最好使用自定义数据库查询。有关详细信息,请参阅此处:http://codex.wordpress.org/Class_Reference/wpdb

然后我建议你将结果存储在瞬态中。您不需要在每次加载时运行查询。

http://codex.wordpress.org/Transients_API

答案 1 :(得分:0)

您可以使用WP_Query并调用$ wp_query-> found_posts来查找帖子数。然后执行循环并缓存值。

更多信息:http://codex.wordpress.org/Class_Reference/WP_Query

$query = new WP_Query( array('posts_per_page'=>-1,
'post_type'=>array('post'),
'date_query' => array(array('after' => 'YOUR DATE')),   
'tax_query' => array(
array(
'taxonomy' => 'YOUR TAX'
))));
相关问题