Wordpress Content Limit

Better Wordpress Content Limit

I decided to update mu Wordpress themes Webbutveckling and Webbdesign which I hope I will release in next couple of days when problem concerning content limit in Wordpress occur to me. There is possibility to include more tag: <!–more–> in every post, but what if you have thousands of posts or later want to change place of more tags? You can use the the_excerpt but what if you don’t want to write excerpts?

I search web for solutions and find 3 plugins.

First one http://labitacora.net/comunBlog/limit-post.phps which is basically a function Limits the displayed text length (number of characters)on the index page entries and generates a link to a page to read the full content if it’s bigger than the selected maximum length. Everything fine except that function strips all html tags and put content between<p> and </p> tag. However it produces valid xhtml against The W3C Markup Validation Service.

Next one – Excerpt and Content Word Limit – limits the number of words from posts or excerpts. It even pulls out first image but with actual size and without wordpress align classes. Plugin also takes html tags and that’s its main downfall because it cuts code regardless if tag is open or closed. HTML output is full of errors and even whole layout could break.

Third – WP Limit Posts Automatically – first check if there is a <!–more–> tag and if is not limits post by number of letters, words or just take first paragraph by inserting <!–more–> tag on specified place. There is same problem as with the plugin above. Leaves unclosed html tags.

I obviously wasn’t satisfied so I write small piece of code which do the job: limits content after set number of words, add gettexted more link to the endof it , pull out only wordpress allowed html tags, check if any tag is unclosed and closing it. And here it is:

<?php

////////////////////////////////////////////////////////////////////////////////

// Find and close unclosed xhtml tags

function close_tags($text) {

    $patt_open    = "%((?<!</)(?<=<)[\s]*[^/!>\s]+(?=>|[\s]+[^>]*[^/]>)(?!/>))%";

    $patt_close    = "%((?<=</)([^>]+)(?=>))%";

    if (preg_match_all($patt_open,$text,$matches))

    {

        $m_open = $matches[1];

        if(!empty($m_open))

        {

            preg_match_all($patt_close,$text,$matches2);

            $m_close = $matches2[1];

            if (count($m_open) > count($m_close))

            {

                $m_open = array_reverse($m_open);

                foreach ($m_close as $tag) $c_tags[$tag]++;

                foreach ($m_open as $k => $tag)    if ($c_tags[$tag]--<=0) $text.='</'.$tag.'>';

            }

        }

    }

    return $text;

}

////////////////////////////////////////////////////////////////////////////////

// Content Limit

	function content($num, $more_link_text = '(more...)') {  

	$theContent = get_the_content($more_link_text);  

	$output = preg_replace('/<img[^>]+./','', $theContent);  

	$limit = $num+1;  

	$content = explode(' ', $output, $limit);  

	array_pop($content);  

	$content = implode(" ",$content);  

    $content = strip_tags($content, '<p><a><address><a><abbr><acronym><b><big><blockquote><br><caption><cite><class><code><col><del><dd><div><dl><dt><em><font><h1><h2><h3><h4><h5><h6><hr><i><img><ins><kbd><li><ol><p><pre><q><s><span><strike><strong><sub><sup><table><tbody><td><tfoot><tr><tt><ul><var>');

      echo close_tags($content);

      echo "<p><a href='";

      the_permalink();

      echo "'>".$more_link_text."</a></p>";

}?>

How does it works?

First function function close_tags($text) use php function preg_match_all to match all xml/html tags against a pattern, find unclosed ones and close them.
The other one function content($num, $more_link_text = ‘(more…)’) get the content with the wp build in function get_the_content(), strip images, strip html tags except allowed, then calls function close_tags to close them, get the permalink to post with wp the_permalink() and that’s it.

How to use this?

Copy the code above and paste it in your themes function.php file

In you theme within the loop find the following code

<?php the_content(); ?>

And replace it with

<?php content(100, __('(more...)')); ?>

Where ‘100′ is the number of words to limit content and ‘more…’ is link to full post. Change ‘100′ to whatever number and ‘more…’ to ‘Read more’ or whatever

Comments are allowed and welcomed.
Share and Enjoy:
  • Digg
  • Facebook
  • Google Bookmarks
  • Technorati
  • Twitter
Posted in: blog

32 Comments on “ Wordpress Content Limit ”

  1. JimmyBean October 1, 2009 at 6:48 am

    I don’t know If I said it already but …This blog rocks! I gotta say, that I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I’m glad I found your blog. Thanks, :)

    A definite great read..Jim Bean

  2. Elcoj October 1, 2009 at 11:38 am

    Hi, Everything dynamic and very positively! :)
    Elcoj

  3. cubrikaska October 4, 2009 at 10:19 am

    Absolutamente con Ud es conforme. En esto algo es yo pienso que es la idea excelente.

  4. RobD October 6, 2009 at 9:00 pm

    Super-Duper site! I am loving it!! Will come back again – taking your feeds too now, Thanks. :)

  5. BloggerDude October 9, 2009 at 2:40 am

    I don’t know If I said it already but …Great site…keep up the good work. :) I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I’m glad I found your blog. Thanks, :)

    A definite great read….

  6. Bill Bartmann October 9, 2009 at 4:24 pm

    I don’t usually reply to posts but I will in this case, great info…I will add a backlink and bookmark your site. Keep up the good work!

  7. Bill Bartmann October 9, 2009 at 5:33 pm

    Generally I do not post on blogs, but I would like to say that this post really forced me to do so, Excellent post!

  8. loan October 12, 2009 at 7:31 am

    cool nice site

  9. luc October 21, 2009 at 9:49 pm

    thanks, you rock!

  10. Healthy girl November 1, 2009 at 1:14 am

    Hello there, I would like to know if you have the same function but with the following :
    After a certain number of letters (including spaces) just add the ‘…’. Of course if the number of letters ends up in the middle of a word do include the entire word.

    See what i mean ?

    The reason i’m asking is because limiting by number of words is great but sometimes after a big paragraph it results in a different size.

    I’m trying to limit my text to a defined size.

  11. Bill Cherne November 15, 2009 at 6:26 pm

    Thank you for posting this amazing code. I was previously using the first plug-in you listed, however your plug-in does an amazing job at keeping the existing formatting.

    For those interested, I simply created a .php file in my Plug-ins folder in wordpress, copied and pasted the code listed above and made this piece of functionality a plug-in that can be enabled/disabled as needed.

  12. Used Solar Panels >> Buy used solar panel November 23, 2009 at 11:18 pm

    [... - en.divinedeveloper.com is another useful website of advice. Car insurance claims [... -

  13. WiiBrew November 30, 2009 at 10:23 am

    What I do not believe I see eye to eye with that at all really.

  14. awidea December 6, 2009 at 9:12 pm

    Hi, Why post image does not show when i add this code? Image show on readmore page. please help.

  15. Mladjo December 7, 2009 at 4:28 am

    Hi,
    That’s intended. This piece of code removes images

    $output = preg_replace('/<img[^>]+./','', $theContent);
  16. JT December 14, 2009 at 6:14 pm

    I want the images to show up. But I cant just remove

    $output = preg_replace(‘/]+./’,”, $theContent);

    So how do I modify the code to include the images?

  17. bobdog December 21, 2009 at 6:40 pm

    I have tried getting the image to show too. After exhaustive searches, there is a different approach…

    Use the function, and edit the formatting.php file, as explained in another post,

    http://chadcarr.com/blog/images-in-auto-excerpts-wordpress-cmsms/

  18. Palanikumar December 28, 2009 at 11:47 am

    Replace the $output = preg_replace(‘/]+./’,”, $theContent); with $output = $theContent;

    Hope it will work…

  19. Khen Solomon March 30, 2010 at 11:14 am

    what about if $num > $theContent? Still (readmore)…..

    I like it :)

  20. Simon April 23, 2010 at 2:35 pm

    I currently use:

    the_content(“read more about ” . get_the_title(”, ”, false));

    I would like to keep this and use your function? Also I agree with some people above, how can I keep images?

    Thanks, looks very promising.

  21. George Turnbull April 28, 2010 at 3:34 am

    I have been perusing a few of your posts and have enjoyed it. Keep it up

  22. gino May 10, 2010 at 5:49 pm

    Hi there

    Thanks for the plug in, it seems to work but i only want to display one post at the time.

    if i use your function it overrides the setting in the options

    Can you help?

    Thanks

  23. Mladjo May 10, 2010 at 5:58 pm

    @gino
    You have to make custom query in order to display one post at the time. Please check this http://codex.wordpress.org/Function_Reference/query_posts

  24. How to Create Your first WordPress Theme: Part 2 | Graphic and Web Design Blog May 21, 2010 at 10:17 am

    [...] A tutorial about limiting the content [...]

  25. How to Create Your first WordPress Theme: Part 2 | Cairns Web Design May 22, 2010 at 1:44 pm

    [...] A tutorial about limiting the content [...]

  26. Celestial Empire - ??????WordPress??:?2? May 29, 2010 at 2:27 pm

    [...] A tutorial about limiting the content [...]

  27. Haspshano May 29, 2010 at 11:13 pm

    Just want to say what a great blog you got here!
    I’ve been around for quite a lot of time, but finally decided to show my appreciation of your work!

    Thumbs up, and keep it going!

    Cheers
    Christian, iwspo.net

  28. Kevin Flaker May 30, 2010 at 4:43 pm

    Hello,this is Kevin Flaker,just found your Blog on google and i must say this blog is great.may I quote some of the Post found in your site to my local buddies?i’m not sure and what you think?in any case,Thank you!

  29. Gucci Shoes May 31, 2010 at 10:51 am

    I am new here and looking to meet some nice people.

    Gucci Shoes

  30. Wholesale sunglasses May 31, 2010 at 5:04 pm

    Thank you for sharing I wish I could go somwhere.

  31. Haspshano June 1, 2010 at 5:57 am

    Just want to say what a great blog you got here!
    I’ve been around for quite a lot of time, but finally decided to show my appreciation of your work!

    Thumbs up, and keep it going!

    Cheers
    Christian,Diet Guide!

  32. Fajne Fotki June 1, 2010 at 4:16 pm

    You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material

Leave a Reply

You must be logged in to post a comment.