Add a WordPress-like Read More link to your content


Today I am going to show you how to write your own function which shows teaser text with a “Read more” link. It may not be the best way but it pretty does the intended functionality.

The logic is pretty simple:
Add <!--more--> HTML commented text as it is, any where in the full text. The text before this comment will be displayed as the teaser.
Call the readMore function with the full text and the URL to the full text as parameters.
Lets do it!
First, we are going to write the function. Lets call it readMore, which takes three parameters:

 
/*
* @param $text - the text for which we will show the teaser.
* @param $url - the URL to the full article.
* @param $label - the label for link. Defaults to"Read more..."
*/
function readMore( $text, $url, $label = "Read more..." ) {
   $pattern = "<!--more-->";
   $output  = preg_split( $pattern, $text );
   if ( is_array( $output ) ) {
      return $output[0] . '<p class="readMore"><a href="' . $url . '">' . $label . '</a></p>';
   }

   return '';
}

 

The first line of the function, the $pattern variable contains a Regular Expression (RegEx) which identifies an HTML comment tag with the text “more”. Then I called the PHP’s RegEx version of the split function preg_split which takes a RegEx pattern and the text to apply the pattern to, as parameters and returns an array. the first element (element at index 0) in the resulted array is the teaser of the full text we passed as parameter. Then, return the teaser with a link to the full text. We can give any label we want, instead of “Read more” just pass a string as the third parameter.

I hope this will be helpful for you guys. if so, drop a comment.

Regards.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.