在single.php/sidebar.php中发布X of Y

时间:2011-12-04 作者:Nathan Bunn

有没有办法把“Y中的X”放进我的侧边栏?我想我只能在一篇博客文章(比如检查内容是否为单篇)时显示它,但我希望能够看到我正在查看的文章。在过去的20分钟里,谷歌搜索“wordpress post x of y”给了我很多关于y页中x类或类似内容的信息,所以我想在这里问一下。

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

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();
}
要在模板文件中使用:

<?php my_post_number(); ?>

结束