How To Add Content To The Post Content Using The Filter In WordPress

In this article, we will learn how to add other content to post content using filters.

We are using the the_content hook for the post content filter.

the_content filter:

Syntax:

apply_filters( ‘the_content’, string $content )

– Filters the post content.

Parameters:

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

This filter is used to filter post content after it has been retrieved from the database and before it is printed on the screen.

When using this filter it is important to check if you are 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 a primary post loop that displays the main content for a post, page, or archive. Without this condition, you may inadvertently filter content for custom loops in sidebars, footers, or elsewhere.

Now, add the below code to your theme function.php file.

function codehub_post_content ( $content ) {
    if ( is_single() ) {
        $content .= '<h3>TheCodeHubs</h3>';
        $content .= '<p>Your content added to all Posts.</p>';
        return $content;
    }
 
    return $content;
}
add_filter( 'the_content', 'codehub_post_content');

You can use the is_page and is_singular condition instead of is_single. Another condition also can be used.

Here we give the is_single condition to check whether the current page is a post or not.

is_single():

Syntax:

is_single( int|string|int[]|string[] $post = ” )

Check whether the query is for a current single post.

After adding the above code, visit your site and check all the posts. Apply filter content with the existing post content.

Output:

Thank you very much for reading this article. I hope you find this article helpful.

Submit a Comment

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

Subscribe

Select Categories