PHP Limit Excerpt Length in WordPress with the_excerpt_max_charlength Function

Learn how to use the the_excerpt_max_charlength function in WordPress to limit the length of your post excerpts. Easily define the desired character length for your excerpts.

<?php
function the_excerpt_max_charlength($charlength) {
    $excerpt = get_the_excerpt();
    $charlength++;

    if (mb_strlen($excerpt) > $charlength) {
        $subex = mb_substr($excerpt, 0, $charlength - 5);
        $exwords = explode(' ', $subex);
        $excut = -(mb_strlen($exwords[count($exwords) - 1]));

        if ($excut < 0) {
            echo mb_substr($subex, 0, $excut);
        } else {
            echo $subex;
        }

        echo '...';
    } else {
        echo $excerpt;
    }
}
?>

<?php the_excerpt_max_charlength(250); ?>