In some instances, you may wish to display a specific number of words from a post's content, perhaps in a compact loop for older posts or as part of an asides section in a blog's sidebar. This recipe shows you how to go about it.
First, open or create your functions.php
file. This file resides in your theme's root directory. You're going to create a custom template tag for your theme, and the functions.php
file is the proper place to do so. Inside of your functions.php
file, place the following code:
<?php function limited_the_content($number_words = 200) { global $post; $stripped_content = strip_tags($post->post_content); $words = explode(' ', $stripped_content); if( count($words) < $number_words ) { echo $stripped_content; } else { $words = array_slice($words, 0, $number_words); echo implode(' ', $words); } } ?>
You'll use this function in place of the_content
to display your post's content. Open one of your...