Using WP’s “the_content” function and filter

Using WP's "the_content" function and filter
Published: by Renier Delport
Collection(s): Coding, Website Development

When the the_content() function is called in WordPress template files, the entire content of the post or page is displayed. By hooking some code in the form of a function into the the_content filter, the content can have custom HTML added in various ways.

This is an ongoing post. Please suggest corrections, explanations, etc. in the comment section at the bottom of this page.

Themes and plugins can use the the_content() function in various places, as long as it is in The Loop. When this function is called, the entire content section of a post or page is collected from the database before it is modified by a series of filters (see later). In its simplest form, the content is displayed using:

<?php // to display the content of a post/page
  the_content();
?>

Using the_content() parameters

By looking at the the_content() function’s code reference, two optional parameters can be used to change the behaviour the content is displayed:

the_content($more_link_text, $strip_teaser);

The the_content() parameters are used as one of two ways to create WordPress ‘excerpts’ or teasers. Using these parameters are only useful on ‘non post type pages’ (i.e. non-single pages, e.g. archive pages, search page, index page, etc. Although the effects of these parameters are customised on each post or page’s editing window, it will not be effective on “single” pages. For this reason, the the_content() parameters will not be discussed further.

The the_content filter

By looking at the the_content() function’s code reference, the function does two main things: collect the ‘raw’ content, and applies it to the_content filter.

$content = get_the_content( $more_link_text, $strip_teaser );
$content = apply_filters( 'the_content', $content );

In other words, before content is displayed using the the_content() function, (by default) it is first ran through a series of ‘filters’ – called the the_content filter.

This series of filters adds paragraph tags, auto-embed videos, expand shortcodes, etc. The the_content filter contains filters that are added by WordPress itself, but plugins and themes can also add their own filters. This means each WordPress website will have a unique set of filters.

Content can also be displayed in WordPress without passing the ‘raw’ content through the the_content filter:

echo get_the_content();

Adding filters to the the_content filter

Additional custom filters can be added to the list of filters in the the_content filter. To register a new filter, the following code is added to the (child) theme’s functions.php file:

add_filter( 'the_content', 'filter_function_name' );

By looking at the the_content filter’s code reference, an optional priority parameter can also be used to affect the order at which the added filter will be executed:

add_filter( 'the_content', 'filter_function_name', 10 );

If not set, the default value is 10. Setting a low priority, i.e. a large number (e.g. 99), will already have processed all the default filters. This number can also be used to prioritise custom filters (i.e. 99 will run before 100).

Appending HTML to the content

Web developers popularly need to add and/or remove things from the content before it is displayed. After registering a new filter to the the_content filter, functions can be used to achieve this. To, for example, add a custom HTML segment to the top and the bottom of the current content, the following function can be used:

add_filter( 'the_content', 'bts_filter_content_sample' );
function bts_filter_content_sample( $content ) {
  $html_segment = '<p>This will be added to the top and bottom of all post and page content.</p>';
  $content = $html_segment . $content . $html_segment;
return $content;
}

A function, in this case bts_filter_content_sample, allows the current content ($content) to be added as input, which can be returned after it is modified. $content is a string value and can be manipulated using PHP. After its modification, $content needs to be returned at the end of the function.

Appending HTML inside paragraph tags

A significant development, while the raw content is ran through the default content filters, is that paragraph (<p>) tags are added. The filter responsible for this is called the wpautop() function.

This might be important because the paragraph tags will make appended HTML display outside the paragraph. By modifying the filter function, custom HTML can be added within these tags too. Two examples include ‘bolding’ the first letter of the first paragraph and adding an ‘endstamp’ next to the last sentence of the last paragraph.

To, for example, add a span element tag around the first letter of the first paragraph, the following function can be used:

add_filter( 'the_content', 'bts_element_first_letter_sample' );
function bts_element_first_letter_sample( $content ) {
  $first_char = substr($content, 3, 1);
  $content = substr($content, 4); // trim first 4 characters
  $content = '<p><span class="first-letter">' . $first_char . '</span>' . $content
return $content;
}

Assuming the first paragraph starts with a <p> tag, this function will obtain the first character as the 4th character of the string, trim the first 4 characters and append the modified version back. There might be many other ways to achieve the same result.

To, for example, add a HTML segment at the end, but on the inside of last paragraph, the following function can be used:

add_filter( 'the_content', 'bts_insert_last_sample' );
function bts_insert_last_sample( $content ) {
  $search = '</p>';
  $replace = ' This will be the last sentence.</p>';
  if( ( $pos = strrpos( $content , $search ) ) !== false ) {
    $search_length = strlen( $search );
    $content = substr_replace( $content , $replace , $pos , $search_length );
  }
return $content;
}

Assuming the last paragraph ends with a </p> tag, this function will find the last occurrence of this tag and replace it with the modified version. There might be many other ways to achieve the same result.

Similar code reasoning principles can be used to add HTML or subtract HTML in other areas of the original content.

Setting conditions for filters

Adding filters to the_content filter will affect the content in all the places the the_content() function is used. For example, both posts and pages will use the same function to display their content. There might be times a content filter only needs to be applied for a specific post type.

The is_singular() function returns a Boolean (true/false) value and can be used in PHP conditional statements to distinguish post types. According to the is_singular() function’s code reference, the slug of the post type can be entered (as a string) to be able to check if it is that specific post type:

is_singular( $post_types = '' );

If used without attributes, it will check whether the it is a post type (e.g. is a post, page or attachment). If the $post_types parameter is specified, the function will additionally check if the query is for the posts types specified:

function filter_function_name( $content ) {
  if (is_singular( 'post' )) { // i.e. is post
    // do something with $content
  }
  elseif (is_singular( 'page' )) { // i.e. is page
    // do something else with $content
  }
  elseif (is_singular( 'advert' )) { // i.e. is advert post type
    // do something else with $content
  }
  else { // i.e. is none of the above
    // do something else with $content
  }
return $content;
}

Other WordPress functions can also be used to set conditions in filters.

More website development related posts

Discover the easy way to send bulk SMS from your PC, Mac or mobile device
Discover the easy way to send bulk SMS from your PC, Mac or mobile device
16 August 2018
Using the latest in technology, WinSMS offers cost effective messaging solutions that business owners can apply to their businesses and benefit from.

Save, share & Disqus

Use the buttons below, on the left or the bottom of this page to share this post. Your comment is important, but don't be a shit. Keep it constructive and polite.

Comment via Disqus

Disqus is a worldwide comment hosting service for web sites and online communities. This secure platform ensures a pleasant commenting environment which is manageable from one account. Use the Login button to sign up.
About the author
Renier busies himself with improving his English writing, creative web design and his websites, photoshopping, micro-electronics, multiple genres of music, superhero movies and badass series.