17

I'm working on WordPress where I have following code to get posts within loop.

        <?php
                $posts = $woo_options['woo_latest_entries'];
                query_posts('post_type=post&category_name=company');
                if ( have_posts() ) : while ( have_posts() ) : the_post(); $count++;

        ?>

        /// Post Content Goes Here //

        <?php endwhile; endif; ?>

Which Output posts inside Loops something like this...

Post Goes Here ....

Other Post Goes Here ....

Another Post Goes Here ....
.....

What I want is to print current posts index number within loop. Example

 1. Post Goes Here ....

 2. Other Post Goes Here ....

 3. Another Post Goes Here ....
 .....

How Can I Achieve This ? Thanks.

EDIT

Ohh ! I can do it this way ..

<?php 
echo $wp_query->current_post +1; 
?>

Is there any other / Better way ?

17

Actually I want to assign ID's as per post index !

Here's your code that I modified.

<?php

global $wp_query;

$posts = $woo_options['woo_latest_entries'];
query_posts('post_type=post&category_name=company');

if ( have_posts() ) : while ( have_posts() ) : the_post();  $count++;
    $index = $wp_query->current_post + 1;

?>
    <div id="my_post_<?php echo $index; ?>">

        <!-- Post Content Goes Here -->

    </div>

<?php endwhile; endif; ?>
  • It seems like this answer provided the essence of the answer that lead to the solution. – New Alexandria Mar 30 '16 at 16:38
4

If it's just an esthetic thing and you don't need to use the count variable for further coding, you can just wrap your posts in an ol tag :

<?php if ( have_posts() ) : ?>

    <ol>

        <?php while ( have_posts() ) : the_post(); ?>

            <li> <!-- Post Content Goes Here --> </li>

        <?php endwhile; ?>

    </ol>

<?php endif; ?>
  • Actually I want to assign ID's as per post index ! – MANnDAaR Jun 23 '11 at 9:09
  • @MANnDAaR, that's exactly what it does. If your loop has 10 posts, you'd see an ordered list, numbered from 1 to 10. (see example here) – mike23 Jun 23 '11 at 9:15
3

for some reason, you already have a counter variable in the loop; if this is not used for other purposes, simply echo it:

<?php echo $count.'.'; ?> /// Post Content Goes Here // 
1

Hi I bumped onto this thread, wondering how to do that too. Found out it's bloody easy. In the main template file, for example index.php, declare a variable $post_idx before the loop, and within the loop increment that var. Like this:

<?php $post_idx = 0; while ( have_posts() ) : the_post(); ?>
  <?php
    get_template_part( 'content', get_post_format() );
    $post_idx++;
  ?>
<?php endwhile; ?>

Then in your content template (for example content.php) that is executed everytime within the loop, just make $post_idx global and then use it to your needs:

global $post_idx;
print "<p>{$post_idx}</p>";

That's it!

  • You should prefix global variables to avoid naming collisions. – fuxia Oct 10 '12 at 16:43
0

I was looking to do the same thing, but outside the loop. Basically I wanted to be able to find out the index of a post from its ID. Here's what I came up with:

<?php
function sleek_get_post_index ($post) {
    $allPosts = get_posts([
        'post_type' => $post->post_type,
        'numberposts' => -1
    ]);

    $index = 0;

    foreach ($allPosts as $p) {
        $index++;

        if ($p->ID == $post->ID) {
            break;
        }
    }

    return $index;
}

This was purely for design as the client wanted numbers next to the posts, even if the post was by itself in a "featured post" box. I also added a leading zero using: <?php echo str_pad(sleek_get_post_index($post), 2, '0', STR_PAD_LEFT) ?>.

0

Even if this question is old, I'll lay this here in case someone coming from a Google Search needs a more flexible answer.

Over the time, I developped a solution to be WP_Query or global query agnostic. When you use a custom WP_Query, you are confined to use only include or require to be able to use the variables on your $custom_query, but in some cases (which are most cases for me!), the template parts I create are some times used in a global query (such as archive templates) or in a custom WP_Query (like querying a custom post type on the front page). That means that I need a counter to be globally accessible regardless of the kind of query. WordPress doesn't make this available, but here's how to make it happen thanks to some hooks.

Place this in your functions.php

/**
 * Create a globally accessible counter for all queries
 * Even custom new WP_Query!
 */

// Initialize your variables
add_action('init', function(){
    global $cqc;
    $cqc = -1;
});

// At loop start, always make sure the counter is -1
// This is because WP_Query calls "next_post" for each post,
// even for the first one, which increments by 1
// (meaning the first post is going to be 0 as expected)
add_action('loop_start', function($q){
    global $cqc;
    $cqc = -1;
}, 100, 1);

// At each iteration of a loop, this hook is called
// We store the current instance's counter in our global variable
add_action('the_post', function($p, $q){
    global $cqc;
    $cqc = $q->current_post;
}, 100, 2);

// At each end of the query, we clean up by setting the counter to
// the global query's counter. This allows the custom $cqc variable
// to be set correctly in the main page, post or query, even after
// having executed a custom WP_Query.
add_action( 'loop_end', function($q){
    global $wp_query, $cqc;
    $cqc = $wp_query->current_post;
}, 100, 1);

The beauty of this solution is that, as you enter in a custom query and come back in the general loop, it is going to be reset to the right counter either way. As long as you are inside a query (which is always the case in WordPress, little did you know), your counter is going to be correct. That is because the main query is executed with the same class!

Example :

global $cqc;
while(have_posts()): the_post();
    echo $cqc; // Will output 0
    the_title();

    $custom_query = new WP_Query(array('post_type' => 'portfolio'));
    while($custom_query->have_posts()): $custom_query->the_post();
        echo $cqc; // Will output 0, 1, 2, 34
        the_title();
    endwhile;

    echo $cqc; // Will output 0 again
endwhile;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.