Created
March 29, 2014 19:45
-
-
Save jbutko/9861570 to your computer and use it in GitHub Desktop.
WP, single.php: Post X of Y in single.php / Post Counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
// Call from anywhere | |
<?php my_post_number(); ?> | |
// From http://wordpress.stackexchange.com/questions/35522/post-x-of-y-in-single-php-sidebar-php#new-answer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a way to modify this so that it shows post X of Y in that category? I've looked around and tried tweaking it myself with no luck.