Change excerpt length according to the title length

In WordPress is it possible to change the excerpt length depending on how long the title is?

I simply call the title like so:

Read More
<?php the_title(); ?>

And the excerpt:

 <?php html5wp_excerpt('html5wp_index'); // in my functions.php I set the length ?>

functions.php

function html5wp_index($length);
{
    return 25;

}

So if the title was 15 characters then the excerpt would only be 10 for example?

Related posts

Leave a Reply

1 comment

  1. This should do the trick for you. Just place it in your functions.php file. Currently it would affect all posts or pages where the_excerpt(); is being used, but you could wrap it in a conditional to isolate it. Just read the comments in the code for some further explanation of what’s happening.

    <?php
    
    function aw_new_excerpt_length($length) {
    
        // get the post title and find its string length
        $str = get_the_title();
        $titleLength = strlen($str);
    
        // check if length is longer that 10 characters
        // and return an excerpt length for more or 
        // less than 10
        if($titleLength > 10) {
        return 5;
        } else {
            return 3;
        }
    }
    
    // then add the filter to change the excerpt length
    add_filter('excerpt_length', 'aw_new_excerpt_length');
    
    ?>
    

    Just change the numbers to set it to your specification.