Using WordPress ‘the_content’ PHP filter

The the_content WordPress PHP filter allows you to modify the post content after it’s retrieved from the database and before it’s displayed on the screen.

Usage

add_filter('the_content', 'your_custom_function');
function your_custom_function($content) {
    // your custom code here
    return $content;
}

Parameters

  • $content (string): The content of the current post.

More information

See WordPress Developer Resources: the_content

Always use is_singular(), in_the_loop(), and is_main_query() conditionals to avoid unintentionally filtering content in custom loops.

Examples

Append a custom text to the end of each post

This code appends “Thank you for reading!” to the end of each post.

add_filter('the_content', 'append_custom_text');
function append_custom_text($content) {
    if (is_singular('post') && in_the_loop() && is_main_query()) {
        $content .= '<p><strong>Thank you for reading!</strong></p>';
    }
    return $content;
}

Add social sharing buttons to the bottom of a post

This code adds social sharing buttons below the post content.

add_filter('the_content', 'add_social_sharing_buttons');
function add_social_sharing_buttons($content) {
    if (is_singular('post') && in_the_loop() && is_main_query()) {
        $sharing_buttons = '<div class="social-sharing-buttons">...</div>';
        $content .= $sharing_buttons;
    }
    return $content;
}

Display an ad after the second paragraph

This code inserts an ad after the second paragraph of each post.

add_filter('the_content', 'insert_ad_after_second_paragraph');
function insert_ad_after_second_paragraph($content) {
    if (is_singular('post') && in_the_loop() && is_main_query()) {
        $ad_code = '<div class="ad-placeholder">...</div>';
        $content = preg_replace('/(<p>.*<\/p>){2}/', '$0' . $ad_code, $content);
    }
    return $content;
}

Wrap images with a custom class

This code wraps all images in the post content with a custom class called “my-custom-image-class”.

add_filter('the_content', 'wrap_images_with_custom_class');
function wrap_images_with_custom_class($content) {
    if (is_singular() && in_the_loop() && is_main_query()) {
        $content = preg_replace('/<img([^>]+)>/', '<div class="my-custom-image-class"><img$1></div>', $content);
    }
    return $content;
}

Remove all shortcodes from the post content

This code removes all shortcodes from the post content before it’s displayed.

add_filter('the_content', 'remove_all_shortcodes');
function remove_all_shortcodes($content) {
    if (is_singular() && in_the_loop() && is_main_query()) {
        $content = strip_shortcodes($content);
    }
    return $content;
}