How to Limit Content in WordPress

By BANAGO » WordPress » February 3rd, 2010

Have you seen those cool magazine style WordPress themes around this days? They are just cool. You might have noticed that they sometimes show a few words of the post, this is for sure not the default WordPress excerpt showing that because the default excerpt length is set to 55 words and manually excerpting every post would be a great time consumer. So, what are this guys putting together to get that cool effect on their sites by controlling the length of the content? Well, as a WordPress freelancer, I have been needing that feature myself and today I’m going to share with you how to have that feature on your site.

There are three different approaches to limit your excerpt or content in WordPress that you must know:

1. WordPress’s Approach

WordPress developers have provided us lately with a tool to limit the excerpt. I do not use it myself as I’m more conformable with another approach as I find this a little limited. To change excerpt length using the default WordPress excerpt limit approach you have to use the excerpt_length filter and add the following code to functions.php file in your theme:

1
2
3
4
5
6
7
function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');

Every time you will use the_excerpt(); on your code it will output an 20-word text string for you. Right now you’ve got a question, don’t you? I know, I had it too. The question is: What if I want to use the 20-word excerpt in some places on my theme, but still be able to use the 55-word one? Or just have two or three different-length exerts to use on my theme? Well, if that is the case, the default approach is not for you, so continue reading.

2. StudioPress’s Approach

I don’t really know who came up with this approach originally, but I know that the guys over at StudioPress use it on their themes. This function is called the_content_limit(). This is how the code that will go into the functions.php file looks like – lengthy huh?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {

$content = get_the_content($more_link_text, $stripteaser, $more_file);

$content = apply_filters('the_content', $content);

$content = str_replace(']]>', ']]>', $content);

$content = strip_tags($content);

if (strlen($_GET['p']) > 0) {

echo "

";

echo $content;

echo " <a href="";</p> <p>      the_permalink();</p> <p>      echo "">"."Read More →</a>";

echo "

";

}

else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) {

$content = substr($content, 0, $espacio);

$content = $content;

echo "

";

echo $content;

echo "...";

echo " <a href="";</p> <p>        the_permalink();</p> <p>        echo "">".$more_link_text."</a>";

echo "

";

}

else {

echo "

";

echo $content;

echo " <a href="";</p> <p>      the_permalink();</p> <p>      echo "">"."Read More →</a>";

echo "

";

}

}

Now we have to call that function because, off course, we are not going to use the default the_excerpt(); function. Here:

1
<?php the_content_limit(20, "[Read more]"); ?>

Pretty simple to use and offers you the possibility to auto-generate a Read More … of you choice.

C.bavota’s Apprach

C.bacota – I don’t know his real name – has produced a couple of great code snippets to limit the content for both the_content() and the_excerpt(). As you may already know, the_excerpt() gets 55 words from the_content() but get rids of all the HTML tags on it, be it links, images or whatever. So, this guy produced a script that allows you to choose to use the text-only version or the html-rich version to limitedly display. I find this functions really cool and easy to use and I have been using them ever since they were produced. This is how the block of code that goes into functions.php looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Limit the content to certain number of words.

function excerpt($num) {
$limit = $num+1;
$excerpt = explode(' ', get_the_excerpt(), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."...";
echo $excerpt;
}
// Limit the content to certain number of words.

function content($num) {
$limit = $num+1;
$content = explode(' ', get_the_content(), $limit);
array_pop($content);
$content = implode(" ",$content)."...";
echo $content;
}

The above code is quite cool, but has two limitation: The first block of code, will not allow you to have a custom excerpt longer than 55 words, the same as the_excerpt() does, and the second one will bump image into your shorten content if you are using images in the original one. However, Mr. C.Basoda eventually thought about his and produced later a revised version of the code that will allow you to use more than 55 words and not get images on the wrong place there. Here is the revised code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)&gt;=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'...';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`[[^]]*]`','',$excerpt);
return $excerpt;
}

function content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)&gt;=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('/[.+]/','', $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]&gt;', ']]&amp;gt;', $content);
return $content;
}

And finally here is how you use this fantastic piece of code:

1
2
3
4
5
6
7
<?php excerpt('20');?>

// or

<?php content('20');?>

The end

We are finally done.  I would also like to make clear that the approaches I presented so far are not necessary all the existing or possible ways to achieve content limitation, however this is what I know and what I thought was of value to share with you. Thanks for reading.

25 Responses to How to Limit Content in WordPress

  1. There is a bug with Studiopress’ approach. Either you or they did not escape some of the double quotes in the echo statements, resulting in some echo statement treated by php as a normal string(check the code). I made some corrections and displayed it as follows, adding the [title] and [rel] attributes so that it will help with validation:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    ', ']]>', $content);
    $content = strip_tags($content);
    
    if (strlen($_GET['p']) > 0) {
    echo "";
    echo $content;
    ?>
    <a href="" rel="bookmark" title="Permanent Link to ">Read More &rarr;
    $max_char) && ($espacio = strpos($content, " ", $max_char ))) {
    $content = substr($content, 0, $espacio);
    $content = $content;
    echo "";
    echo $content;
    echo "...";
    ?>
    <a href="" rel="bookmark" title="Permanent Link to ">
    <?php
    }
    
    else {
    echo "";
    echo $content;
    ?>
    <a href="" rel="bookmark" title="Permanent Link to ">Read More &rarr;
  2. It seems your comment form has cut off some of some of my code. Delete this if im wrong.

  3. Sumon says:

    Great Tricks @ Thanks for share this @!

  4. Cippo says:

    Here’s another one!

    function word_limiter($text, $limit = 200) {
    // short enough?
    if( strlen($text) <= $limit) {
    return $text;
    }
    // check if last word is full
    if( substr($text, $limit, 1) == ' ') {
    return trim( substr($text, 0, $limit));
    }
    // hard cut
    $cut = substr($text, 0, $limit);
    // remove last word
    $words = explode(' ', $cut);
    array_pop($words);
    return implode(' ', $words);
    }

    and use it like this:

    $str = 'your string';

    echo word_limiter($str);

    Hope you find this useful!

    You can see it live on http://cippodesign.com/blog ( in latest comment <> :)

  5. Cippo says:

    I forgot to tell, the long code goes in functions.php and the $str and echo goes within your loop!

    Cheers!

  6. ali says:

    Dear Banago, I have used “C.bavota’s Apprach”. I installed his latest plug-in. Then I went through loop.php and and changed “the_content()” to “content(’100′)” which is my post limitation. But when I write a new post with 105 words it shows all!

    I even edited single.php with same changes. But there is no limitation on my posts.

    Can you help me please?

  7. Ali says:

    Thanks for prompt answer. As a matter of fact, I am trying to test it on my PC (localhost, made by WampServer).
    I am gonna make a weblog for my school students. But I need to limit their posts up to 100 words only.

    And … I have left these optinons without any change:
    What do you want to appear after your excerpt?
    What do you want to appear after your content?
    What do you want your read more link to be?

  8. Ali says:

    Dear Banago,
    I have asked my friend to give me a piece of his website to install wordpress and I did same on the real host. But it does not work! If you want I can give you the login address, admin and password to check the code. I really don’t know what is wrong. I have changed “the_content()” to “content(’100′)” in loop.php.

  9. BANAGO says:

    Yes, please send me the the login data so that I can have a look what’s wrong.

  10. Ali says:

    Thank you very much for your kindness and help. I wish all the best for you.

  11. Majalah says:

    Usually I use custome excerpt wp plugin to re-setting default wp excerpt. But, thanks for the tutorial.

  12. Evil says:

    Ok that’s cool
    but how i can limit WordPress rss posts summary to 10 words only .

  13. Adi says:

    Thanks for sharing I was searching for this.

    Now I can limit content in my blog.

    Thanks again

  14. relax tone says:

    Yes, this will allow you to do that. The code simply wraps your content in divs, so if you’re content looked like this:

  15. Martyr2 says:

    Normally I don’t comment on code I find like this, but C.bavota’s “fix” is actually a bit clumbsy and full of problems.

    1) They tack on the ellipses but then strips it out using the preg_replace. It also strips out all periods in the content. [.+] matches one or more periods.

    2) Then what is with the line str_replace(‘]]>’, ‘]]>’, $content);? This is looking for ]]> and replacing it with ]]>? Useless line.

    Remove that last line and fix up the preg_replace and you will have a much more solid solution.

  16. I wasn’t happy with any of the above either. Went trolling for a solution that I could plugin to both StudioPress (client a) and c.bavota magazine premium (client b referred to me by client a).

    I still haven’t found the solution that could (plugin) to either theme, however, I did like the look of this plugin (that doesn’t work with either).

    http://wordpress.org/extend/plugins/limit-post-add-on/installation/

    Would like to find a way to make it work in either, or hard edit them to work with it (requires a change to Studiopress lib/formating.php file )

    still searching thats when I came across your article but didn’t see your own solution if it is published yet…

  17. mick warnes says:

    Banago, I have spent a long while getting this to work properly in my site and have found your scripts to be the most useful. However, I lost access to my admin and on removal on our plugin, it started to work again, not sure why as it was working ok for a while.
    I then used the code above in my function file and this was doing it all apart from the ‘.’ were being stripped from the URL to the image, So I have removed this from your code
    $content = preg_replace(‘/[+]/’,”, $content);
    and it seems to work.
    I now feel that I have bodged it to work and wondered if it was a setting in WordPress that is the issue.

  18. vichet says:

    Thanks for sharing. I have made my own version. I would like to share it here. It can close html tags, show or hide images/shortcodes, re-enable auto video emed in wordpress, strip tags, read more links. Please visit it here:

    http://www.nisaiy.com/17/how-to-word-limit-wordpress-posts/

  19. Renee says:

    Used Banago’s solution and it worked a treat for controlling how much text is displayed in some cluster style pages I have.

    Did encounter a problem though – each page of mine has an [intro] shortcode to style the first par. This function striped out any content that was in the shortcode.

  20. san says:

    Hi Banago,

    Thanks for your post.

    I want to limit contents through a page id. I mean I have a page where I want to print limited contents from different pages using page id in each separate section for each page.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2007 - 2009 Baki Goxhaj Powered by WordPress and WPlancer