Simple way to setup excerpts on your WordPress index page

This is something I’ve had to do several times. I’m pretty sure there are a few plugins to handle this, but changing one line of code is much better than having to load a whole plugin file and execute it. This is an easy way to setup an auto-excerpt for each post on you WordPress index (front page of you blog). This way will take a certain length off the front of your posts and display it. If you look into the index.php file of most themes, somewhere in the file you will find a line of php that calls the WordPress function the_content(). This will display the whole post by default. What I normally do is comment this out (remember, never delete anything!) by adding two backslashes before this particular part, like so: [code lang=”php”] // the_content(); [/code] The next thing to do is call php’s native substr() method. This will take a given string and strip out a sub-string, given the starting position and length of the sub-string. I use the WordPress function get_the_content() to return the post’s content, rather than printing it. This is an example of how I’m using this method on this site: [code lang=”php”] echo substr(get_the_content(), 0, 160) . "…"; [/code] This basically takes the first 160 characters of a post (starting at position 0), echoes (or prints) it to the browser, and then adds three continuous periods (…), just to signal that there is more to the post. This is usually enough to get the first sentence or two. This will help keep the length on your index page down and you don’t have to remember to write an excerpt for every post. You can see this in use of the front page of this site –

here.

Leave a Reply

%d bloggers like this: