Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Show a Read More Link Based on the Number of Words


Go to End


3 Posts   2203 Views

Avatar
Andrew Houle

Community Member, 140 Posts

7 April 2009 at 12:49am

I have the following basic setup: A Staff Page (page type) that display Staff (dataobject). I have the Staff Page displaying the Staff dataobjects the way I'd like. They have all the necessary info and a Bio. I limit the bio to 50 words and have a read more link to show the full bio if someone clicks on it. However I would only like to show the 'Read More' link only if the Bio word count is above 50. I'm assuming I could write a function in the Staff Page controller for that. That would return a boolean for the word count above or below 50, but I'm having trouble writing that. Can anyone point me in the right direction, or know the code I would need?

Thanks in advance!

Avatar
snaip

Community Member, 181 Posts

11 May 2009 at 11:44pm

any idea ?

Avatar
Andrew Houle

Community Member, 140 Posts

20 June 2009 at 2:56am

For the sake of completion here is the code I ended up using for this. I'm not sure it's optimal, but it did the trick:

function WordCount($str){
		 $words = 0;
		 $str = eregi_replace(" +", " ", $str);
		 $array = explode(" ", $str);
		 for($i=0;$i < count($array);$i++)
		 {
			 if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i])) 
				 $words++;
		 }
		 return $words;
	 }

function ReadMore() {
		$Bio = $this->Bio;
		$BioWords = $this->WordCount($Bio);
		if ($BioWords > 50)
			return True;
		else
			return False;
	 }

Of course you would replace the Bio stuff with Content or whatever field you were using. Then in the template you can use:

<% if ReadMore %><a href="$Link" >Continue Reading</a><% end_if %>