Access get_the_title() from ‘excerpt_length’ filter

Allow me to purpose an alternative. Instead of setting the excerpt’s length for all the posts, let’s just trim it for individual posts. Shall we?

For this very purpose, we can use get_the_excerpt filter. If you look at the corresponding page about this filter, you notice that the code example is using is_attachment(), which means you have access to the global $wp_query.

We hook into the get_the_excerpt filter, and use a custom function to trim the excerpt:

add_filter( 'get_the_excerpt', 'custom_excerpt_more' );
function custom_excerpt_more( $excerpt ) {
    // Get the current post
    $post = get_post();
    // Calculate the length of its title
    $charlength = strlen( $post->post_title );
    $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 ) {
            $output = mb_substr( $subex, 0, $excut );
        } else {
            $output = $subex;
        }
        $output .= ' ...';
        return $output;
    } else {
        return $excerpt;
    }
}

There you go. Your excerpt is now trimmed by its post title.