1

I have created a custom excerpt length in my functions.php, I would like to extend this function to increase the excerpt length of the first post in a loop.

My function at the moment:

/* Change Excerpt length */
function custom_excerpt_length( $length ) {
    return 30;
}

Was thinking of something along these lines

function new_excerpt_length($length) {
    global $post;
    if ($post-> FIRST POST?)
        return 50;
    else
        return 20;
}

Is there a way of getting post count from $post->?

1

2 Answers 2

2

Use the current_post property of the WP_Query object:

function new_excerpt_length($length) {
    global $wp_query; // assuming you are using the main query
    if ( 0 === $wp_query->current_post)
        return 50;
    else
        return 20;
}

The function may need further tweaks to avoid interfering with other queries in unintended ways, but that is the basic idea.

2
  • Fantastic, am I right you can apply this to different queries then?
    – James
    Commented Dec 3, 2015 at 15:09
  • @James : Yes but you'd have globalize the query variable beforehand. WordPress globalizes $wp_query for you. If you need to use this in specific queries there are probably better ways to do it.
    – s_ha_dum
    Commented Dec 4, 2015 at 2:38
2

Another approach:

function custom_excerpt_length( $length ) 
{
    static $instance = 0;
    return ( in_the_loop() && 0 == $instance++ ) ? 50 : 20;
}

where we use simple counting inside the loop.

Your Answer

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

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