Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Two Excerpt Lengths? Possible?

Hi.

I need to have the excerpt for the first blog post on the homepage longer than the others experts.

I've been searching the internet for a solution, but I've been unsuccessful so far.

can anyone help?

Thanks Kerry

3 Answers

Andrew Shook
Andrew Shook
31,709 Points

Kerry, do you need a longer or shorter excerpt? As far as I know there is no way to have two excerpt lengths at the same time. You can, however, write a custom function that will do it for you. Give this a try, but be warned I didn't test the code myself:

<?php 

    function custom_excerpt($length = 55){
        $content = explode( " ", get_the_content());
        echo implode(" ", array_slice($content, 0, $length - 1));
    }
?>

If you add this to your theme's functions.php you should be able to call it in any of you template files.

Actually, now that I'm looking more at it, this should work too:

<?php

// functions.php

add_filter( 'excerpt_length', 'two_different_excerpt_lengths' );
function two_different_excerpt_lengths($current_excerpt_length)
{
    if ( $post->ID === wp_get_recent_posts( array(
        'numberposts' => 1,
        'orderby' => 'post_date',
        'order' => 'DESC',
    ) )[0] ) {
        return 45;
    } else {
        return 55;
    }
}

I'm not sure if this will work, but it's worth a shot.

<?php

// functions.php

add_filter( 'excerpt_length', `two_different_excerpt_lengths` );
function two_different_excerpt_lengths($current_excerpt_length)
{
    if ( is_post() ) {
        return 45;
    } else {
        return 55;
    }
}

This code should give you an excerpt of 45 words on blog posts, and 55 words on everything else. You can change the conditions to be whatever you need. As I said before, it might not work, so don't try this out in production. :)

Andrew Shook
Andrew Shook
31,709 Points

That's a great way to do it if she need to change it by post type.