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;