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 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..."
* @author LogicGhost (http://logicghost.blogspot.com)
*/
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>';
   }}

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.

Advertisements

Have your say

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s