Simple, free resources to help you build a better WordPress website.

Sign up for our newsletter.

Custom Excerpt with Specific Character Length

If you’ve ever been frustrated with the standard WordPress excerpt function ( the_excerpt() ), I feel your pain. I typically try to avoid using the_excerpt() and instead use the_content() with a manual break, but sometimes you need a more controlled solution for clients that may not know how to add manual breaks or use excerpts for the power of good, not evil. Well, for me, this was just the case.

I was looking for a solution where I can define a custom excerpt with a character length cutoff and came across a handy bit of code posted on Chris J. Davis’ blog that I was able to customize a bit for my own purposes. I thought I’d share the result below:

function custom_excerpt($chars) {

    global $post;

    $text = get_the_content();

    $text = $text . " ";
    $text = strip_tags($text);

    if( strlen($text) > $chars )
        $ellipsis = true;

    $text = substr($text,0,$chars);

    $text = substr($text,0,strrpos($text,' '));

    if( $ellipsis == true )
        $text = $text . "...";

    echo $text;

The difference between mine and Mr. Davis’ code is that mine checks to see if the original length of the content was long enough to require an ellipsis at the end. If not, it just leaves it alone and outputs the text. Hope it helps if you’re frustrated with WordPress’ default excerpt function.

Leave a Reply

Your email address will not be published. Required fields are marked *