Php

Add a Wordpress-like Read More link to your content

27 May 2011Junaid Qadir2 min read224 Words
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:

1 
2/*
3* @param $text - the text for which we will show the teaser.
4* @param $url - the URL to the full article.
5* @param $label - the label for link. Defaults to'Read more...'
6*/
7function readMore( $text, $url, $label = 'Read more...' ) {
8 $pattern = '<!--more-->';
9 $output = preg_split( $pattern, $text );
10 if ( is_array( $output ) ) {
11 return $output[0] . '<p class='readMore'><a href='' . $url . ''>' . $label . '</a></p>';
12 }
13
14 return '';
15}

 

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.

Share this post
How do you feel about this article?