Showing posts with label auto node title. Show all posts
Showing posts with label auto node title. Show all posts

Monday, July 4, 2011

How to make titles optional and generate title from body text

Head to automatic nodetitles , download and install the module.

Goto /admin/content/node-type/entry under the "Automatic title generation" field set select the second or third option and paste the code below.

//the least number of words in a scentence when trying to extract a complete scentence
$w_sentence= 1;
//if the scentence obtained contains more words than this it will be truncated to this many words and "..."
$w_wordnum = 10;
//if the number of characters after all truncation is above this number it will be truncated to this many characters and "...",  This is to protect agains extremely long words
$w_maxchar = 50;

// this is the name of the cck node token you want to use for example"
$bodyfield = '[field_sms_text-formatted]';


function summarize($paragraph, $limit)
    // cuts the 
       {
           $tok = strtok($paragraph, " ");
           while($tok)
           {
               $text .= " $tok";
               $words++;
               if(($words >= $limit) && ((substr($tok, -1) == "!")||(substr($tok, -1) == ".")))
                   break;
               $tok = strtok(" ");
           }
           
           return ltrim($text);
       }

function shorten_string($string, $wordsreturned)
     /*  Returns the first $wordsreturned out of $string.  If string
    contains more words than $wordsreturned, the entire string
    is returned.
    */
    {
    $retval = $string;    //    Just in case of a problem
    $array = explode(" ", $string);
    if (count($array)<=$wordsreturned)
    /*  Already short enough, return the whole thing
        */
        {
        $retval = $string;
        }
    else
    /*  Need to chop of some words
        */
        {
        array_splice($array, $wordsreturned);
        $retval = implode(" ", $array)."...";
        }
    return $retval;
    }     

// if somone managed to put in html we have to clean it out
$bodyfield = strip_tags($bodyfield);    

// multiple spaces in my editor were correctly converted to hardspaces but it confuses drupal so we need to remove them
$bodyfield = str_replace(' ', " ", $bodyfield);
$bodyfield = trim($bodyfield);


$bodyfield = summarize($bodyfield, $w_sentence);
$bodyfield = shorten_string($bodyfield, $w_wordnum);

// to protect agains extremely long words we also have a character based rule
if(strlen($bodyfield) > $w_maxchar )
    {
    $bodyfield = substr($bodyfield,0,$w_maxchar)."...";
    }
    
print check_plain($bodyfield);