Customizing WordPress Posts by Editing the WordPress Loop

The WordPress Loop

The Loop refers to the section of PHP code used to display posts. Below we took the loop statement from the WordPress Index.php file that we use to start custom WordPress themes with. Here is what a basic loop looks like:


		
id="post-">

'); ?> Posted in |

If you are familiar with PHP, then you can see how the loop is basically a while loop that says while there are posts, post them. It is as simple as that. However, there are all sorts of things you can do to customize the loop in WordPress. We will do some simple customizations to the WordPress loop next.

As the author of this tutorial and a programmer, I recently had a job where I had to build a custom WordPress installation that required me to alter the loop. The client wanted a very basic blog that only had posts of a very simple nature. They wanted posts with no comments, no other navigation links on the page and a simple white on black custom theme. All the blog was to consist of was two WordPress pages basically. They wanted the home page to be the multiple post page WordPress normally uses as the default home page. Then they wanted the normal single post page as well to show the entire post when a reader clicks the “read more” link from the home page or multiple post page (same thing).

Making a Custom Home Page with Multiple Posts

The multiple post page is normally the default home page for WordPress, so that part doesn’t require any changes. This particular job requires a summary of four lines of the post text be shown for each post. That does require some changes. It further requires that images be displayed in posts at a specific size only. That also requires some customizing. Here we list the requirements for the multiple post home page for this project:

1. Multiple posts on home page
2. If post has text, only four lines of text should show followed by a “read more” link.
3. If post contains images, they are to be displayed at height of 184px with fluid width.
4. The footer for each post should consist of only basic meta data including the author name and date only.
5. There is to be only a header, four links of content, images, read more links and meta footers on the page for each post, all else needs to be taken off.

Those are our basic project requirements without going into too much detail to keep this tutorial brief enough to be educational without covering too many topics at once. In this tutorial we are only going to cover how to make the modifications for those five specs.

Spec one is already done for us as it is the default behavior of WordPress, so we will start with spec two.

Locate the index.php file inside of your active theme’s folder. The default WordPress installation is going to show all posts on the home page and they are likely to display the entire posts. For this project we only want four lines of text, so we need to modify the index.php page in the WordPress site’s theme folder for the selected theme. In our case we used a custom theme template we use for developing all custom themes.

the_content & the_excerpt WordPress Loop Functions

In order to limit the number of lines of text shown on our multiple post page, we need to edit the inner workings of the loop. Locate the function called the_content in the loop code inside the index.php page. This is the code that controls how many lines of code are shown on the page for each post. The the_content function does not allow us the freedom to control the amount of text shown. The the_excerpt function does however. The first thing we need to do then is replace the_content with the_excerpt. Once you do that, we need to customize the WordPress core so that when we call the_excerpt function it does what we want it to do. In this case we want it to display four lines of text and resize images if they are present.

Modifying the wp_trim_excerpt Function

In order to make the_excerpt function work as we described above, we actually have to make changes to the wp_trim_excerpt function instead of the the_excerpt function as you may have thought. That is because the WordPress core can be tricky and functions are called from within functions. If you follow the trail of functions you will find that the code you need to change is in the wp_trim_excerpt function. The wp_trim_excerpt function is located in the formatting.php file which is in the wp-includes directory.

You should never actually modify a function in the WordPress core. Instead of modifying it, we are going to replace it. First take the original function and then make changes to it as needed. Here is the original wp_trim_excerpt function:

functionwp_trim_excerpt($text = '') {
	$raw_excerpt = $text;
	if ( '' == $text ) {
		$text = get_the_content('');
		$text = strip_shortcodes( $text );
		$text = apply_filters('the_content', $text);
		$text = str_replace(']]>', ']]>', $text);
		$excerpt_length = apply_filters('excerpt_length', 55);
		$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
		$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
	}
	returnapply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}

First, you need to understand the function in order to be able to replace it. Skip down to the fourth line of the function and you can see it calls the get_the_content function which is linked to the get_content function we replaced in our index.php file earlier. This is significant because what it does is sets the $text variable equal to the original post content. The rest of the function basically alters that text as WordPress sees fit. That’s what we are going to change. We need to alter the code after line four so that it allows images and four lines of text.

The first thing we need to do in order to replace the above function is to write a new one that does the same thing but with our changes implemented. Take a look at our replacement function then we will explain:

Function altered_excerpt($text) {
global $post;
if ( '' == $text ) {
                $text = get_the_content('');
                $text = apply_filters('the_content', $text);
                $text = str_replace('\]\]\>', ']]>', $text);
                $text = strip_tags($text, '');
                $excerpt_length = 80;
                $words = explode(' ', $text, $excerpt_length + 1);
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, '[...]');
                        $text = implode(' ', $words);
                }
        }
return $text;
}

Adding Images to Post Excerpts

In the above code, notice lines seven and eight. Those are where the major differences are. Those lines are the lines that allow us to both allow images in multiple post pages and to allow four lines of text in the same posts.

First in line seven you see:

$text = strip_tags($text, '');

That replaces the strip_shortcodes function in the original wp_trim_excerpt function in which the new altered_excerpt function replaces. WordPress actually previously used the strip_tags function for this, but in version 3.3.1, they now use the strip_shortcodes function instead. The problem with strip_shortcodes is that it doesn’t allow us to enter exceptions like strip_tags does. Notice how we added “” to the strip_tags function above. That makes it allow the img tag and no others which is exactly what we want!

Changing the Amount of Text Displayed in Multiple Post Pages

Next in line eight of the altered_excerpt function above we set the number of words to show from each post. Here you may have to do a little trial and error to see how many words you want. In our case, we want four lines and we figured out that setting it to 50 words works nice. We set the value in line eight to 50.

Activating a New Function

Now to make the new altered_excerpt function work, we first need to deactivate the wp_trim_excerpt function that it replaces. Then we need to activate the new function. To deactivate the old function, add the following code after your new function in functions.php:

remove_filter('get_the_excerpt', 'wp_trim_excerpt');

Then to activate the new function add this code after the above line in functions.php:

add_filter('get_the_excerpt', 'altered_excerpt');

Now you have a new function which replaces the original wp_trim_excerpt function and allows images in posts and restricts the amount of text to four lines.

Fixing the Images to Show at Equal Heights

We still have one problem with our new multiple posts page. The images are all different sizes and can look messy. To fix this we are going to show you how to add some JavaScript code to fix the images so they are all the same height. You don’t want to change both the height and width because it will make your images no longer proportionate. Just setting the height attribute of the image tag, the width will automatically scale to the proportionate value. The same happens with height if you only set width. For this to work, you have to leave one dimension out. So we set the height and make sure that there is no width attribute set by unsetting it with JavaScript.

Adding JavaScript Code to a WordPress Theme

First we need to cover the correct way to include JavaScript in a WordPress theme. The correct way is to include the code inside the head section of the header.php file in your active theme’s directory. You want to include the code in the head tag in-between the Meta tags and the first CSS link. In our case we are adding JavaScript that will resize all images in posts in our index.php page. Since the index.php page includes the header.php page, it will work great. Here is the code to resize images in multi post pages:

The above JavaScript code works by grabbing the article tag first which holds the images we are seeking. We put the article tags in an array then count them. Next we used a for loop to iterate over the article tags and find the img tags in each post. We put the img tags in an array as well and count them. Then we iterate the imgarray and resize each image as we do so. That does the trick! We just wrote our function to resize all images in our home page of multiple posts.

Now we need to call our function for it to work. In this case we need the function called from the index.php file, so we put the following code at the very bottom of index.php so it is executed after the images have loaded:

That is it! we have effectively altered our WordPress posts without using a plug-in or adding a new theme. We did it by editing the WordPress core files some while basically leaving the core untouched. That is the proper way to do it. Altering the core functionalities permanently is frowned upon and not recommended because you could accidentally cause damage to some areas of WordPress that you had not intended to.

Using a Plug-in to add Images Instead

Adding images to post excerpts is tricky as you can see from the above exercise. This is mainly because the the_excerpt function does not allow for any images at all, only text. So how do we get images to show? Well you could do as we did above to get the most flexibility or you could use a plug-in. If you want to use a plug-in, there are few that could fit the bill such as the “Thumbnail For Excerpts” plug-in found here. We suggest that you customize the loop as we did though because it offers you much more flexibility. If you are not comfortable with PHP and the inner workings of WordPress, then you may choose a plug-in instead. It’s up to you in the end, so happy blogging!

About 

A serial entrepreneur in projects large and small across multiple industries. Mike is the CEO of Terran Marketing which specializes in WordPress based websites.