Wordpress: Text Excerpts with PHP


/ Published in: PHP
Save to your folder(s)

Create excerpts from text block from your wordpress content and add links page / post from the guid.


Copy this code and paste it in your HTML
  1. /**
  2. * usage:
  3. * $txt = new($post->post_content, 50, 'Read in full', '<span class="readmore">', '</span>', '<a><span>');
  4. * echo $text->createExcerpt();
  5. *
  6. */
  7.  
  8.  
  9. class text{
  10.  
  11. public $text;
  12. public $length;
  13. public $allowedTags;
  14. public $readMoreText;
  15.  
  16. //create internal variables from those passed to the class
  17. function __construct($text = '',
  18. $length = 50,
  19. $readMoreText = 'Read In Full...',
  20. $before = '',
  21. $after = '',
  22. $allowedTags = '<a>') {
  23.  
  24. $this->text = $text;
  25. $this->length = $length;
  26. $this->readMoreText = $readMoreText;
  27. $this->before = $before;
  28. $this->after = $after;
  29. $this->allowedTags = $allowedTags;
  30.  
  31. }
  32.  
  33. //shorten text to required length
  34. public function shortenText() {
  35. //explode the string into an array of the length we want
  36. if (count(explode(' ', $this->text)) > $this->length)
  37. {
  38. $textArray = explode(' ', $this->text, $this->length);
  39. //remove the excess string from the end of the array
  40. array_pop($textArray);
  41. //create a string from the array
  42. $textString = implode(' ', $textArray);
  43. //cleaning up
  44. unset($textArray);
  45. //return
  46. return $textString . '... ';
  47. }
  48. else
  49. {
  50. return $this->text;
  51. }
  52. }
  53.  
  54. //remove tags and other.
  55. public function cleanText($text){
  56. //strip the text of html tags, except those we want
  57. $strippedText = strip_tags($text, $this->allowedTags);
  58. //remove [] and their content
  59. $strippedText = preg_replace('`\[[^\]]*\]`','',$strippedText);
  60. //return
  61. return $strippedText;
  62. }
  63.  
  64. //create output
  65. public function createExcerpt(){
  66. global $post;
  67.  
  68.  
  69. //create output
  70. $output = '';
  71. $output .= $this->cleanText($this->shortenText());
  72. if($this->readMoreText !== '')
  73. {
  74. $output .= $this->before;
  75. $output .= ' <a href="'. $post->guid .'" title="'. $this->readMoreText . ': '. $post->post_title .'">'. $this->readMoreText . '</a>';
  76. $output .= $this->after;
  77. }
  78. return $output;
  79. }
  80.  
  81. }//end class//

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.