Adding Automatic ‘Read More’ to Drupal Trimmed Views

Written by Karl Binder on August 18, 2011

One thing that has been niggling at me this week is the fact I could not get a trimmed Drupal view field – such as a node body – to show a read more link if it was shortened using the teaser format. I could add the node link field, but this would always show, even if the field was not shortened by using the teaser. So the way around it was to put some PHP into the view template file for that field, in this case a ‘views-view-field–latestnews–body.tpl.php’ file.

<?php
// First of all create a teaser version of the body field
$teaser = node_teaser($output);

// show the teaser on the page
print $teaser;

// now below compare the teaser to the original full field, and if it's different, show a more link
if ($teaser!=$output) {
print '<br/>';
 print l('Read more >', drupal_get_path_alias('node/'.$row->nid),array('attributes' => array('class' => 'moreTeaserLink')));
}
?>