How to set character limit on the_content() and the_excerpt() in wordpress

You could use a WordPress filter callback function. In your theme’s directory, locate or create a file called functions.php and add the following in:

Use the code in your function.php

<?php   
  add_filter("the_content", "ab_content_limit");

  function ab_content_limit($content)
  {
    // Take the existing content and return a subset of it
    return substr($content, 0, 300);
  }
?>

or you can create your own excerpt function and use function name in your theme.

Use the code in your function.php file.

function ab_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;
    }
}

use below code in theme files

<?php ab_max_charlength('300'); ?>

Leave a Reply

Your email address will not be published.