I try to get the current post index number and echo the number of this lesson(post)in a series of lessons(category).
I'm inside the loop on single.php page
my code looks like this:
$args = array(
'cat' => 22,
);
$query = new WP_Query( $args );
echo $query->current_post;
echo $query->post_count;
the "$query->post_count" works great and give me the number of the posts that are inside this category, but the "$query->current_post" don't work and give me "-1" all the time in every post...
what i'm doing wrong?
I try to get the current post index number and echo the number of this lesson(post)in a series of lessons(category).
I'm inside the loop on single.php page
my code looks like this:
$args = array(
'cat' => 22,
);
$query = new WP_Query( $args );
echo $query->current_post;
echo $query->post_count;
the "$query->post_count" works great and give me the number of the posts that are inside this category, but the "$query->current_post" don't work and give me "-1" all the time in every post...
what i'm doing wrong?
Share Improve this question asked Apr 21, 2015 at 11:09 Erez LiebermanErez Lieberman 3183 silver badges14 bronze badges2 Answers
Reset to default 2What you are seeing is totally expected as you are trying to get the value of $current_post
outside the loop. Before and after the loop, the value of $current_post
will always be set to -1
.
To get the proper value, you need to check $current_post
inside the loop, the first post will be 0
and this will increase by one on every iteration of the loop.
For more info on creating the Post X of Y
thing, check out these site searches on this issue
Thanks, Pieter.
Based on this answer, I made some changes to work on specific category. Here is my final code:
<div class="lessonNumber">
<?php
class MY_Post_Numbers {
private $count = 0;
private $posts = array();
public function display_count() {
$this->init(); // prevent unnecessary queries
$id = get_the_ID();
echo __('שיעור', 'swgeula') . ' ' . $this->posts[$id] . ' ' . __('מתוך', 'swgeula') . ' ' . $this->count;
}
private function init() {
if ( $this->count )
return;
$parent_cat = get_the_category()[0];
$parent_cat_id = $parent_cat->cat_ID;
global $wpdb;
$posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND ID IN ( SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = '" . $parent_cat_id . "' ) 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();
}
my_post_number();
?>
</div>