Drupal 6 Trim Node Content

webadmin's picture
Drupal

While working on an aggregation site recently I needed to find a way to truncate the length of aggregated posts so that they only showed the first 200 or so characters of the post. However, I also wanted the split point in the post to occur at the end of a whole word, as opposed to part way through a word, and add some visual indication that there was more still to read.

The solution:
I'll first show the entire solution and then walk through how it works afterwards.

In your theme's node.tpl.php file the node content will most usually be output using code similar to:

<?php print $content ?>

Find this code and replace it with the following code (minus the opening and closing php tags which are just used here to improve the formatting):

<?php
$mywords = explode(" ", $content);
$finalstring = "";
foreach($mywords as $word) {
if(strlen($finalstring) <= 197) {
$finalstring = $finalstring . " " . $word;
} else {
$finalstring = $finalstring . " [...]";
break;
}
}
echo $finalstring;
?>

Baca Juga

13 years 9 months ago
14 years 7 months ago