the graphic design blog that speaks the truth

A common feature popping up on many WordPress websites and blogs is to have a landing page for the blog where the latest few blogs posts are displayed.

Furthermore, these pages tend to only show the first few lines of text of said posts. This post will show you an extremely easy way to display a certain amount of the post content whilst maintaining any HTML tags (including links and formatting) that it might contain.

The Code

I wasn’t lying when I said this was easy. The traditional way to display a posts, or indeed a page’s content is to use:

<?php the_content(); ?>

Now to only display a certain amount of the content we can do the following:

<?php $content = get_the_content();
echo substr($content, 0, 600)."...."; ?>

This code simply grabs the content and passes it to a variable named $content. We then use the substr php function to echo a certain amount of this variables content (our content). In the above case this is 600 characters (letters and spaces)

We’re not quite done yet though. This code will ignore any html tags we have in our content like paragraphs and links. To ensure that these html elements are maintained, we simply add the nl2br php function into our code. So our final code snippet becomes:

<?php $content = get_the_content();
echo nl2br(substr($content, 0, 600))."...."; ?>

Note: Above I have added a few full stops to indicate to the user there is more content to read. This is purely for display purposes and can be removed / adjusted to your requirements.

ABOUT THE AUTHOR

SHARE THIS ARTICLE

Voice Your Opinion

Thanks for your comment, it will appear here once it has been moderated.