Last updated March 19, 2012. Created on July 17, 2008.
Edited by bfr, JuliaKM, LinL, pkej. Log in to edit this page.

The Automatic Nodetitles module can be used to hide a node title field and generate node titles. When the Token module is installed, you can include tokens as part of a title.

An easy title substitution is to use the first words of the body field of a node to substitute for its title. For example, if your node body is "This is a test article. I am writing a test article here. Woohoo!!!!" and the title is limited to 10 words using auto_nodetitle and the script below, your node title would become "This is a test article. I am writing a test..."

Drupal 6

The following should be pasted into the "Pattern for the title:" field. "Evaluate PHP in Pattern" should be set to true.

<?php
 
$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;
?>

Here is what entering the code looks like within the Drupal 6 administrative interface.


Drupal 7

The following code can be entered on a content type edit page. For example, for an "article" content type, the code would be entered at admin/structure/types/manage/article.

<?php
$limit
= 10;
$text = $node->body[$node->language][0]['value'];

$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;
?>

Here is what entering the code looks like within the Drupal 7 administrative interface.

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.

AttachmentSize
auto_nodetitle_d7.png90.26 KB
auto_nodetitle_d6.png49.3 KB

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

jfrederick’s picture

Thank you so much for writing this! Auto node titles in D7 displays body as an available token, but it doesn't actually work. This code worked perfectly.

tvilms’s picture

Hi, with the Automatic Nodetitles module enabled, I can no longer set the node:body:value using Rules. Has anyone been able to set the node body value using PHP? If so, please share your approach. Thanks!