How To Add Content Before Or After Posts With The The_Content Filter
The the_content filter runs every time WordPress prints the content of a post. Hook into it to add a call to action, an author box, an ad or any extra block without editing every post.
Add a box after every blog post
function lotgrafix_after_post_content( $content ) {
if ( is_singular( 'post' ) && in_the_loop() && is_main_query() ) {
$content .= '<div class="lotgrafix-cta"><p>Enjoyed this post? <a href="' . esc_url( home_url( '/contact/' ) ) . '">Contact us</a></p></div>';
}
return $content;
}
add_filter( 'the_content', 'lotgrafix_after_post_content' );
The three conditions make sure the box only appears on single posts, inside the main loop, and not in widgets or secondary queries.
Add content before the post
function lotgrafix_before_post_content( $content ) {
if ( is_singular( 'post' ) && in_the_loop() && is_main_query() ) {
$reading_time = ceil( str_word_count( wp_strip_all_tags( $content ) ) / 200 );
$content = '<p class="lotgrafix-reading-time">' . absint( $reading_time ) . ' min read</p>' . $content;
}
return $content;
}
add_filter( 'the_content', 'lotgrafix_before_post_content' );
Insert content after the second paragraph
function lotgrafix_insert_after_paragraph( $content ) {
if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
return $content;
}
$insert = '<div class="lotgrafix-inline-box">Your banner here</div>';
$parts = explode( '</p>', $content );
if ( count( $parts ) < 3 ) {
return $content;
}
foreach ( $parts as $index => $part ) {
if ( trim( $part ) ) {
$parts[ $index ] .= '</p>';
}
if ( 1 === $index ) {
$parts[ $index ] .= $insert;
}
}
return implode( '', $parts );
}
add_filter( 'the_content', 'lotgrafix_insert_after_paragraph' );
Notes
- Use the priority argument to control the order. The default is
10, and a higher number runs later. - Never call
the_content()orapply_filters( 'the_content' )inside this filter, or it will loop forever. - Excerpts and feeds also pass through filters, so check the conditions carefully.


