Last active
April 24, 2022 16:13
-
-
Save davidwebca/c0bd19ce5a7cc36332ad8ed40ba9c4ec to your computer and use it in GitHub Desktop.
Global current_post counter, WP_Query agnostic
This file contains 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
<?php | |
/** | |
* Create a globally accessible counter for all queries | |
* Even custom new WP_Query! Include inside functions.php in your theme. | |
* This allows you to have a post counter available in your sub-templates | |
* accessible even if you use get_template_part(); | |
* | |
* Example | |
* | |
* global $current_loop_post_index; | |
* while(have_posts()): the_post(); | |
* echo $current_loop_post_index; // Will output 0 | |
* the_title(); | |
* | |
* $custom_query = new WP_Query(array('post_type' => 'portfolio')); | |
* while($custom_query->have_posts()): $custom_query->the_post(); | |
* echo $current_loop_post_index; // Will output 0, 1, 2, 3 | |
* the_title(); | |
* endwhile; | |
* | |
* echo $current_loop_post_index; // Will output 0 again | |
* endwhile; | |
*/ | |
/** | |
* Initialize your variables | |
*/ | |
add_action('init', function(){ | |
global $current_loop_post_index; | |
$current_loop_post_index = -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 $current_loop_post_index; | |
$current_loop_post_index = -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 $current_loop_post_index; | |
$current_loop_post_index = $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 $current_loop_post_index 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, $current_loop_post_index; | |
$current_loop_post_index = $wp_query->current_post; | |
}, 100, 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment