Following on from my previous question: (Calling a custom excerpt function in a local loop ), I am not understanding why echo $wp_query->current_post;
in template.php
is returning -1
for every post when it seems to me it is in the loop and should each individual post number?
I need to get the post number of each post in the loop so I can target a specific post and manipulate the excerpt. I have tested everything else and it seems to be working. Could anyone explain this behaviour to me and how I could return the post number for each post? Code below, thanks.
home.php
<div>
<?php
$args = array(
'posts_per_page' => 5,
'post_type' => 'post',
'cat'=> 2,
'wpse_query_id' => 'home_post_loop' // Special parameter
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
get_template_part( 'template-parts/content', 'template' );
}
wp_reset_postdata();
}
?>
</div>
template.php
<div class="excerpts">
<div class="post-text">
<div class="entry-content">
<span class="entry-text">
<?php
the_excerpt();
echo $wp_query->current_post;
?>
</span>
</div><!-- .entry-content -->
</div>
</div>
functions.php
<?php
add_action( 'pre_get_posts', 'wpse_excerpt_length_handler' );
function wpse_excerpt_length_handler( $query ) {
if ( isset( $query->query['wpse_query_id'] ) && 'home_post_loop' === $query->query['wpse_query_id'] ) {
add_filter( 'excerpt_length', 'wpse_custom_excerpt_loop', 999 );
function wpse_custom_excerpt_loop( $length ) {
global $wp_query;
if ( $wp_query->current_post == 0 && ! $wp_query->is_paged ) {
$length = 20;
} else {
$length = 10;
}
return $length;
}
?>