显示类别内的帖子x/y

时间:2013-06-14 作者:Nathan

我目前在我的单个博客帖子中使用这个类来获取帖子总数和我的帖子数量(帖子89/90,等等)

class MY_Post_Numbers {

private $count = 0;
private $posts = array();

public function display_count() {
    $this->init(); // prevent unnecessary queries
    $id = get_the_ID();
    echo sprintf( \'<div class="post-counter">Post number<span class="num">%s</span><span class="slash">/</span><span class="total">%s</span></div>\', $this->posts[$id], $this->count );
}

private function init() {
    if ( $this->count )
        return;
    global $wpdb;       
    $posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = \'publish\' AND post_type = \'post\' ORDER BY post_date " ); // can add or change order if you want 
    $this->count = count($posts);

    foreach ( $posts as $key => $value ) {
        $this->posts[$value] = $key + 1;
    }
    unset($posts);
   }
}
$GLOBALS[\'my_post_numbers\'] = new MY_Post_Numbers;
function my_post_number() {
$GLOBALS[\'my_post_numbers\']->display_count();
}
我想让它特定于类别。这可能吗?因此,不是90分之89,而是10分之8,因为它只在该帖子的特定类别内查看。

1 个回复
SO网友:Rarst

原始SQL很不方便。

您可以使用get_posts() (或WP_Query 包裹)的\'fields\' => \'ids\' (参见fields parameter ) 对于轻量级计数,同时保留与它接受的所有参数的兼容性,包括category parameters

结束

相关推荐

Restrict query_posts by Date?

要根据页面视图显示最流行的帖子,我使用以下代码(source):<?php query_posts(\'meta_key=post_views_count&orderby=meta_value_num&order=DESC\'); if (have_posts()) : while (have_posts()) : the_post(); ?> <li><a href=\"<?php the_permali