Show just the first n characters from the content of a wordpress page / post

Few days ago i got an unexpected requirement: show only the first n characters from the content of a page.  My first question was : “Why not use the excerpt?” and the answer was that the client doesn’t want to add also an excerpt…So, i started to research for a solution. After trying a lot of ideas this is with what i came up in the end:


$n_limit=250;
$caption_text = get_the_content();
if ( ( $n_limit> 0 ) && ( strlen( $caption_text ) > $n_limit) ) {
$caption_text = substr( $caption_text, 0, $n_limit);
$caption_text = substr( $caption_text, 0, strrpos( $caption_text, ' ') );
if ( strlen( $caption_text ) > 0 ) {
$caption_text .= ' ... ';
}
}
echo $caption_text.'<a href="'.get_permalink().'">Continue reading →</a>';

…and it worked for me 🙂

1 Comment
  • khdoakwk
    December 21, 2012

    Absolutely composed subject matter, thankyou for information .

Leave a Reply