0

I've been using this little snippet from another answer on here to limit the number of characters that display in the excerpt;

add_filter('wp_trim_excerpt', function($text){    
    $max_length = 140;
    if(mb_strlen($text, 'UTF-8') > $max_length){
        $split_pos = mb_strpos(wordwrap($text, $max_length), "\n", 0, 'UTF-8');
        $text = mb_substr($text, 0, $split_pos, 'UTF-8');
    }

    return $text;
});

The problem is that I now have multiple excerpts and one global character limit isn't a viable option anymore.

Is there a way that I could define the character limit on individual excerpts? (So, for example, one excerpt could show 150 characters while another shows 200?)

1

Put the following code into functions.php:

// TRUNCK STRING TO SHORT THE STRINGS
function trunck_string($str = "", $len = 150, $more = 'true') {

    if ($str == "") return $str;
    if (is_array($str)) return $str;
    $str = strip_tags($str);    
    $str = trim($str);
    // if it's les than the size given, then return it

    if (strlen($str) <= $len) return $str;

    // else get that size of text
    $str = substr($str, 0, $len);
    // backtrack to the end of a word
    if ($str != "") {
      // check to see if there are any spaces left
      if (!substr_count($str , " ")) {
        if ($more == 'true') $str .= "...";
        return $str;
      }
      // backtrack
      while(strlen($str) && ($str[strlen($str)-1] != " ")) {
        $str = substr($str, 0, -1);
      }
      $str = substr($str, 0, -1);
      if ($more == 'true') $str .= "...";
      if ($more != 'true' and $more != 'false') $str .= $more;
    }
    return $str;
}


// the_content() WITHOUT IMAGES
// GET the_content() BUT EXCLUDE <img> OR <img/> TAGS THEN ECHO the_content()
// And ADD <a>DETAILS</a>
function custom_excerpt( $Trunckvalue = null ) {
    ob_start();
    the_content();
    $postOutput = preg_replace('/<img[^>]+./','', ob_get_contents());
    ob_end_clean();
    echo trunck_string( $postOutput, $Trunckvalue, true ); ?>
    <a class="read-more" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" rel="bookmark">DETAILS</a>
    <?php
}

Now everything required is ready.

EXPLANATION

As you can understand, in the second or last function we are taking the_content() and excluding the <img/> tags, so that they will appear as the_excerpt(). And then we are passing the trunck value into the new custom excerpt. And using the custom_excerpt() function anywhere we can use our new excerpt.

USAGE

Just where you need to call the <?php the_excerpt() ?>, simply call the <?php custom_excerpt() ?>. If you want to control the excerpt length, just put the length in number like: <?php custom_excerpt(250) ?>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.