Brad Fletcher
Brad Fletcher

Reputation: 3583

Function ShortenTitle

I'm developing within Wordpress but my PHP knowledge is minimal, The title is showing only the 1st word, how to I change it? this is where I believe its being restricted to the 1st word.

function ShortenTitle($title){
// Change to the number of characters you want to display
$chars_max = 100;
$chars_text = strlen($title);
$title = $title."";
$title = substr($title,0,$chars_max);
$title = substr($title,0,strrpos($title,' '));
if ($chars_title > $chars_max)
{
$title = $title."...";
}
return $title;
}
function limit_content($str, $length) {
  $str = strip_tags($str);
  $str = explode(" ", $str);
  return implode(" " , array_slice($str, 0, $length));
}

Upvotes: 0

Views: 46

Answers (2)

SeanWM
SeanWM

Reputation: 16989

if ($chars_title > $chars_max) should be if ($chars_text > $chars_max)

Try this:

function ShortenTitle($title) {
    $title = trim($title);
    $chars_max = 100;
    if (strlen($title) > $chars_max) {
        $title = substr($title, 0, $chars_max) . "...";
    }
    return $title;
}

Cleaned it up a bit.

Upvotes: 1

Matt Dodge
Matt Dodge

Reputation: 11142

The trim function removes whitespace from the end of the string, I assume this is what you are trying to do with this

$title = substr($title,0,strrpos($title,' '));

Also, you should probably trim before computing the length, just to be safe/accurate. Try this:

function ShortenTitle($title){
    // Change to the number of characters you want to display
    $chars_max = 100;
    $new_title = substr(trim($title),0,$chars_max);
    if (strlen($title) > strlen($new_title)) {
        $new_title .= "...";
    }
    return $new_title;
}

Upvotes: 1

Related Questions