apply_filters( 'the_content', string $content )

Filters the post content.


Description Description


Parameters Parameters

$content

(string) Content of the current post.


Top ↑

Source Source

File: wp-includes/post-template.php

View on Trac


Top ↑

Changelog Changelog

Changelog
Version Description
0.71 Introduced.

Top ↑

More Information More Information

This filter is used to filter the content of a post after it is retrieved from the database and before it is printed to the screen.

Top ↑

Usage Usage

When using this filter it’s important to check if you’re filtering the content in the main query with the conditionals is_main_query() and in_the_loop(). The main post query can be thought of as the primary post loop that displays the main content for a post, page or archive. Without these conditionals you could unintentionally be filtering the content for custom loops in sidebars, footers, or elsewhere.

add_filter( 'the_content', 'filter_the_content_in_the_main_loop' );

function filter_the_content_in_the_main_loop( $content ) {

    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
        return $content . "I'm filtering the content inside the main loop";
    }

    return $content;
}

 



Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by joncomputing

    You can choose whether $content will have Shortcodes processed before or after your the_content function has executed by setting the Priority in add_filter. The default (10) will process Shortcodes after you have returned $content at the end of your Filter function. A large figure, such as 99, will already have processed Shortcodes before your Filter function is passed $content.

  2. Skip to note 3 content
    Contributed by SeanM88

    Consolidate multiple string replacement filters
    String replacements are a common reason for filtering the_content and with PHP7 you can now consolidate multiple callback functions using preg_replace_callback_array(); if it makes sense to.

    Example:

    add_filter( 'the_content', 'multiple_string_replacements');
    function multiple_string_replacements ( $content ) {
    	if ( is_single() && in_the_loop() && is_main_query() ) {
    		return preg_replace_callback_array([
    			// 1. Removes WordPress injected <p> tags surrounding images in post content.
    			'/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU' => function ( &$matches ) {
    				return $matches[1] . $matches[2] . $matches[3];
    			},
    			// 2. Adds custom data-attribute to <p> tags providing a paragraph id number.
    			'|<p>|' => function ( &$matches ) {
    				static $i = 1;
    				return sprintf( '<p data-p-id="%d">', $i++ );
    			},
    		], $content );
    	}
    	return $content;
    }
    

You must log in before being able to contribute a note or feedback.