Wednesday, October 14, 2009

Module snippets: Automatic Nodetitles

If you have content that doesn't have a title per se, you can use Automatic Nodetitles (http://drupal.org/project/auto_nodetitle) to generate the title. In the simplest form you could use a token like [nid] to insert a node id. However I've found that using just the first n words of the body for the title is a good option.
Here is some code which you can paste into the "Pattern for the title:" field, remember to set "Evaluate PHP in Pattern" to true.
$limit = 10;
$text = $node->body;

$text = strip_tags($text);
     
$words = str_word_count($text, 2);
     
$pos = array_keys($words);
      if (
count($words) > $limit) {
         
$text = substr( $text, 0, $pos[$limit]);
         
$text = trim( $text );
         
$text = rtrim( $text, '.' );
         
$text = trim( $text ) . '...';
      }

return 
$text;
?>

(include the php preprocessor tags). For more advanced limits you might create a hidden field for your content type which holds the value of the number of words to insert into the title. That hidden field could be static for all instances of the field, or configurable per insert.

No comments:

Post a Comment