Jump to:

3372 Posts in 998 Topics by 712 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Show a Read More Link Based on the Number of Words

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

Page: 1
Go to End
Author Topic: 1397 Views
  • Andrew Houle
    Avatar
    Community Member
    132 Posts

    Show a Read More Link Based on the Number of Words Link to this post

    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!

  • snaip
    Avatar
    Community Member
    180 Posts
  • Andrew Houle
    Avatar
    Community Member
    132 Posts

    Re: Show a Read More Link Based on the Number of Words Link to this post

    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 %>

    1397 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.