15. May 2011
von Blackbam

A lot of sites want WordPress excerpts to have an accurate length to fit into a specified number of text lines. This can be required for design reasons, for example. The default WordPress excerpt length is managed by a given amount of words (default 70), which can be very imprecicsly when it comes to the actual length. Using the following function, you can get the excerpt by defining an desired amount of characters:

// define the desired amount of characters
$numberOfChars = 140;

// call the function
the_excerpt_max_charlength($numberOfChars);

// the function - copy this to the functions.php-file in your theme for example
function the_excerpt_max_charlength($charlength) {
   $excerpt = get_the_excerpt();
   $charlength++;
   if(strlen($excerpt)>$charlength) {
       $subex = substr($excerpt,0,$charlength-5);
       $exwords = explode(" ",$subex);
       $excut = -(strlen($exwords[count($exwords)-1]));
       if($excut<0) {
            echo substr($subex,0,$excut);
       } else {
       	    echo $subex;
       }
       echo "[...]";
   } else {
	   echo $excerpt;
   }
}

With a slight differentiation this function can not only be used for excerpt, but for a very general way to limit the words of a PHP string by specifying a maximum amount of characters. This is the function for general use:

// Shorten a String pattern to a maximum of characters without breaking words, by giving a String, maximum length and closing pattern if true
function cis_limit_words($pattern,$charlength=200,$after=" [...]") {
   $charlength++;
   if(strlen($pattern)>$charlength) {
       $subex = substr($pattern,0,$charlength-5);
       $exwords = explode(" ",$subex);
       $excut = -(strlen($exwords[count($exwords)-1]));
       if($excut<0) {
            echo substr($subex,0,$excut);
       } else {
            echo $subex;
       }
       echo $after;
   } else {
    echo $pattern;
   }
}

Because it proved to be useful I also provided this to the codex, improvements are welcome.

Share

Dieser Eintrag wurde am 15. May 2011 um 15:15 in der Kategorie WordPress, WP Scripts veröffentlicht. You can book the comments for this article RSS 2.0. Feedback, discussion, commendation and critics are welcome: Write a comment or trackback.


Tags: , ,

No comments yet

Kommentare abonnieren (RSS) or URL Trackback

Leave a comment:

Warning: Undefined variable $user_ID in /home/.sites/609/site1266/web/blackbams-blog/wp-content/themes/SilentWoodsByBlackbam/comments.php on line 92