Snippet: Adding Text to the End of a Post

The WordPress content filter, also known as the_content, is a way to filter post and page content before it is printed to the screen.

As an example, suppose you have a page with the following content:

Hello there!  My name is Mike and I like to eat food.

Add the following code to your theme’s functions.php:

function filter_my_content($content) {
    
    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
        $content = str_replace('food', 'dirt', $content);
    }
    
    return $content;
}

add_filter('the_content', 'filter_my_content');

Now if you refresh the page from earlier you’ll notice the content has slightly changed.

Hello there! My name is Mike and I like to eat dirt.

Wow Mike, you’re gross. Let’s examine the code line by line.

First, we check to make sure we’re inside the main loop on a single post page.  This check ensures that we aren’t filtering content from other things like the sidebar or navigation menus.

Then we use PHP’s str_replace() function to replace the string food with dirt.

Finally, we return the content.  All filters must return something.

Adding Text to the End of a Post

Additional uses for filtering the content include things like appending content to the beginning or end of the content.

The following example adds a paragraph of text to the end of the content on single posts:

function filter_my_content($content) {
    
    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
        $content .= '<p>This was added from a filter function.  Cool!</p>';
    }
    
    return $content;
}

add_filter('the_content', 'filter_my_content');

As you can see, there are many different ways you can use the_content filter to affect the output of the content.