0

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;
}


  ?>
4
  • 1
    No need to create a new question. We can continue this on the original thread. There's an issue with this code that I've corrected with the most recent edit. Commented Jun 6, 2017 at 5:27
  • 1
    you can just use $query->current_post directly. The template code is merely inserted where you call get_template_part (php require() or require_once()). also, $wp_query is not declared anywhere (but also not needed).
    – inarilo
    Commented Jun 6, 2017 at 5:47
  • 1
    you can also just use the_ID();
    – inarilo
    Commented Jun 6, 2017 at 5:50
  • If you don't mind, I'd suggest deleting this question since we've got things straitened out in the other thread (this approach doesn't work since the custom query does not overwrite the global $wp_query instance. The custom variable is available via pre_get_posts, but the issue with the global $wp_query object remains). Commented Jun 6, 2017 at 10:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.