Accessing the post content with the ‘the_content’ filter

Ernest Marcinko Tutorials, Wordpress Leave a Comment

Tutorial level

medium

The “the_content” filter is applied to each post, page and custom post type before printing. You can access this filter just like any others in your theme or plugin.

This filter is giving you access to the entry content – thus you can do whatever you want with it. This is also the general idea of filters in WordPress, to give the programmer access to certain content safely. It's your choice to either alter this content or do nothing with it.

When do you need access to the “the_content” filter?

  • If you want to print something before, or after the content
  • If you want to replace something in the content
  • If you need the content for something, but you don't want to do anything with it

A good example is printing your plugin shortcode before/after the content. I'm sure you have seen plugins with such options on the backend.

Where to code?

It depends on whether you are building a plugin or template:cJaZs5z[1]

  • Anywhere if you are making a plugin
  • The functions.php file if you are making a template

Make a functions file or something if you are using a plugin, the main plugin file will become a mess if you keep pasting code there.

A simple example

Let's print “Hello world” before and after the post content.

function add_hello_below_content($content) {
    return $content . "Hello World!";
}

function add_hello_above_content($content) {
    return "Hello World!" . $content;
}

add_filter('the_content', 'add_hello_below_content', 10, 1);
add_filter('the_content', 'add_hello_above_content', 10, 1);

Simple as that.

Putting a shortcode before/after content

Same thing. You don't need to run the shortcode, just add it to the content string.

function add_your_shortcode_below_content($content) {
    return $content . "[your_shortcode]";
}

function add_your_shortcode_above_content($content) {
    return "[your_shortcode]" . $content;
}

add_filter('the_content', 'add_your_shortcode_below_content', 10, 1);
add_filter('the_content', 'add_your_shortcode_content', 10, 1);

Yep. Nothing special. Now you will be able to print your plugin/theme shortcode straight to the content!

Ernest Marcinko

WordPress developer, javascript enthusiast, photoshop clicker and the founder of wp-dreams.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Human test *