5 Code Snippets for Interacting with WordPress Post Content Effectively

Amid content management systems, there is no software solution more popular than WordPress. The software is currently in use by more users than any of its competitors, including the popular Joomla and Drupal alternatives. More than 36 million websites currently use the software to manage their content, and WordPress is responsible for powering and organizing a whopping 16.7 percent of Alexa's top one million websites.

5 Code Snippets for Interacting with WordPress Post Content Effectively


Given this reputation, it might be easy to assume that WordPress has a number of key ways to organize and interact with website content. That assumption would be correct, as the software pairs big content management features with small code snippets that can easily manage, organize, and present website content effectively.

5 Code Snippets for Interacting with WordPress Post Content

Amid all of the features, large and small, that make WordPress the most popular content management platform in the world, there are a number of must-have code snippets that improve website functionality and content viewing. Astute administrators should implement each of these snippets if they wish to join the ranks of the internet's top websites.

1. Show More Posts and Less Content on the Index Page

One of the hallmarks of any WordPress installation is its default preference to show the latest posts on the blog's homepage. This is actually quite useful, and it's been the preferred way to display content for more than a decade. It can, however, contribute to extremely "long" websites that also come with a pretty lofty file size. That can slow down overall page loading times and cause the most impatient users to go elsewhere for reliable, authoritative content.

This does not need to be the case. In fact, it's possible to show more posts on the website's homepage without sacrificing page length or file size. It's done by replacing whole posts with brief excerpts, and it's as easy as replacing a single WordPress variable in the index.php template.

First and foremost, that index.php template file must be located and opened. This can be done by pointing an FTP client to the following server path, in the vast majority of cases:

/home/public_html/wp-content/themes/YOUR-THEME/index.php

When the file has been opened, look for the following variable within the template file's WordPress Loop:

This displays the post's full amount of content on the index page. It's not necessarily the best way to do things, especially when there's a desire to display a large number of posts to the site's readers. This variable can be replaced with the following one:

As its name implies, this variable will show just an excerpt of the WordPress post's content, rather than the full extent of it. This will display the first 55 words of the post, and then append a "Read more..." link to the end of that excerpt. Interested readers can click that link and be taken to the post's standalone page, via its permalink, where they can finish reading the content.

If 55 words within a WordPress excerpt is simply too short or too long, then it can be modified using a quick edit to the theme-specific functions.php file. That edit defines a custom excerpt length and then appends it to the current excerpt function. Here's how it looks:

function longer_excerpt_length( $length ) {
    return 100;
}
add_filter( 'excerpt_length', 'longer_excerpt_length', 999 );

This code should be pasted right at the top of the theme's functions file. In this case, it will increase the excerpt length from 55 words to a maximum of 100. Administrators can feel free to adjust this as their needs and preferences require.

2. Embrace "Nofollow" for External Links in Post Content

One of the quirks about linking to external websites within WordPress' own post content is that it actually serves to build up the linked-to site's search engine rankings while doing nothing to assist the website that actually places the link in its content. Google recognized this quirk some time ago and, in conjunction with the W3C, created a new link element that will cause Google to ignore links to external websites. Known as the nofollow element, it appears in links like so:

<a href="http://domain.com" rel="nofollow">Link Goes here</a>

Adding this element to every link individually can be a bit taxing, and it's something that most WordPress administrators won't bother to do. Luckily, a code snippet placed into the theme-specific functions.php file can automatically append a nofollow instruction to every link bound for an external website. Simply open the functions file and place the following lines of code at the top of the document:

add_filter('the_content', 'auto_nofollow');

function auto_nofollow($content) {
    //return stripslashes(wp_rel_nofollow($content));

    return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
}

function auto_nofollow_callback($matches) {
    $link = $matches[0];
    $site_link = get_bloginfo('url');

    if (strpos($link, 'rel') === false) {
        $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);
    } elseif (preg_match("%href=S(?!$site_link)%i", $link)) {
        $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);
    }
    return $link;
}

The function above creates a routine that looks for external links only within the body of every post or page. It then filters that content and adds a nofollow instruction only to external links. No such modification will occur when a link involves one of the website's own internal pages. With this modification, a website's search engine optimization can be greatly improved and its rankings at Google and other major search engines will rise accordingly.

3. Creating a More Standards-Valid Image Tag After Upload

Uploading an image to WordPress for inclusion within a post has only gotten easier as the software's developers have focused on a complete overhaul of the Dashboard administration area. Even so, the actual code inserted into a post when an image is uploaded is unnecessarily bulky. Most of it is much too static for current designs, which are rooted in CSS. This code can be modified after being inserted, removing some of the "cruft" so that the current design's stylesheet can do its work.

The typical code produced by an image upload looks like this:

<a href="http://domain.com/wp-content/uploads/2012/08/S7301298.jpg">
    <img src="http://domain.com/wp-content/uploads/2012/08/S7301298-768x1024.jpg" alt="" width="768" height="1024" class="alignnone size-large wp-image-667" />
</a>

This is, indeed, quite bulky. Most of the code contained within the image is unnecessary - especially the code defining an image width and height. The uploaded image code is actually paired with the alignnone class in this case, and that class is what should be used to determine the image's dimensions. With a little cleaning up, the image tag looks much better:

<a href="http://domain.com/wp-content/uploads/2012/08/S7301298.jpg">
    <img src="http://domain.com/wp-content/uploads/2012/08/S7301298-768x1024.jpg" alt="My image description." class="alignnone size-large wp-image-667" />
</a>

So, how does this "clean-up" happen within WordPress? It could certainly be done manually every time an image is uploaded, but that's a big waste of time in most cases. Instead, a function can be added to the theme-specific functions.php file to automatically remove the width and height elements from the inserted img tag.

Open the functions.php file located within the current theme's root folder. At the top of that file, add the following snippet of PHP code:

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
    $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
    return $html;
}

This code will remove the width and height elements from images that are defined as post thumbnails, or featured post images, as well those images that are uploaded for inclusion with a post's content anywhere in the body itself. This will save a considerable amount of time when composing new posts or pages within the WordPress Dashboard.

4. Enable the "Featured Image" Functionality in WordPress

In addition to cleaning up the code for an uploaded image in the Dashboard, WordPress administrators should consider creating a featured image for each post that they create. This featured image can actually be placed into the WordPress Loop by using a simple PHP variable. It can be placed above or below content, pulling users in and giving them a reason to click through an excerpt for the full story.

The featured image is enabled by adding a small bit of code to the current theme's functions.php file, which can be found in the theme's root folder. That is generally at the following server path:

/home/public_html/wp-content/themes/YOUR-THEME/index.php

At the top of that file, the following code should be placed, which will enable the featured image on the "Add Post" page within the Dashboard:

add_theme_support( 'post-thumbnails' );

Small, medium, and large post thumbnail images can also be enabled simply by inserting the following three lines into the theme-specific functions.php file:

the_post_thumbnail('thumbnail'); // Maximum of 150px x 150px
the_post_thumbnail('medium'); // Maximum of 300px x 300px
the_post_thumbnail('large'); // Maximum of 640px x 640px

These lines of code will enable a new box in the right-hand sidebar of the pages that allows for the addition of new posts and pages. A link labeled Upload Featured Image will appear in this box, and can be used to define the featured image for each individual post. The image is then assigned to a PHP variable within WordPress. When placed into the WordPress Loop, it will generate the featured image and make it available for CSS styling. That variable is:

When the tag has been inserted into a WordPress Loop properly, the relevant template file can be saved and uploaded. All that needs to be done after this is to simply style the relevant image class so that the image has the proper dimensions and appearance.

By default, the featured image for a post is given the wp-post-image class by WordPress. Styling the image is easy, then, and looks something like this:

img.wp-post-image {
    max-width: 100%;
    max-height: auto;
    border: 3px solid #fff;
    padding: 1px;
    margin: 0 0 15px 0;
}

With that, the addition of the featured image is complete. Posts will now have an entirely new way to engage readers and pique their interest in the website's latest content.

5. Use an RSS Feed to Display Special Content to Subscribers

Using the theme-specific "functions.php" file, it's possible to inject special content into an RSS feed that can only be seen by those readers who subscribe to the feed as a method of reading the site's content. This is a great way to deliver advertising only to the site's most committed visitors, or simply inject special content or instructions that might help new users work with the site's feed itself.

To do this, simply open functions.php and insert the following code. This code will append a standard block of content to every article contained in the RSS feed:

function feed_message($content) {
    if(is_feed()){
        $content = 'You're reading our RSS feed. For the full version of the site, and the ability to comment, please visit this entry by clicking its title link.';
    }
    return $content;
}
add_filter('the_excerpt_rss', 'feed_message');
add_filter('the_content', 'feed_message');

A simple message explaining the RSS feed's functions will now be added to the bottom of each post. This same code could be used to inject textual advertisements into the feed. Because readers who subscribe to a feed are typically more committed to the site and its ads, this is actually a great way to increase revenues while also increasing access to the site's content on both desktop and portable computing devices.

Conclusion

The five code snippets above are each powerful, yet relatively minor, ways to enhance the way WordPress processes and displays content for end users. Each modification will make life a little easier for site administrators, and will help bolster the website's standing among its regular readers, its new visitors, and the search engines that send people to the site's authoritative content.

Opinions expressed in this article are those of the author and not necessarily those of Onextrapixel.