I am having this issue how to make a limit readable text with a 'read more' link below it. I am making my own cms system as a school project, so i would like to add that feature to it.
I have made so i am able to create an article, but the text just keep going on if i write like 1000 words in one article. I only have a little clue how to make the text limit to 50-100 words.
Anyone have made this before that could help me out how they did it?
The idea is to have two methods GetPreview(id, n)
and GetArticle(id)
where the first returns only first n
words from an Article
with a link to a page that calls second method.
Assuming that $articleText
is the content of your article and a word is considered to be delimited by spaces this is how a part of the GetPreview
function will look like:
$words = explode(" ", $articleText);
if (count($words) <= $n)
return $articleText; //unchanged
$preview = array_splice($words, 0, $n); //n is the number of words
return implode(" ", $preview) . "... <br />" .
<a href=\"ViewArticle.php?id=" . $articleId . "\">Read More </a>";
where ViewArticle.php
should be another page that loads the entire article.
However, this is an example that will work for plain text articles. If your articles contain HTML the method to extract the preview becomes more complex because you don't want it break the content in the middle of a HTML tag.
Another approach, which is actually safer and used in popular CMS like WordPress is to decorate your article with a specific HTML comment like:
<!-- more -->
When you display the entire article you don't have to do anything special because this will not be displayed by the browser (remember, it's a comment).
However, in your GetPreview
method you search for this string and if you find it:
There are multiple advantages of this method: