Content & Posts PHP Beginner

Add a Call-to-Action Box After Every Post

Add the same box to the end of every blog post, such as a newsletter sign-up or a link to your products.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 13 lines
add_filter( 'the_content', function ( string $content ): string {
	if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
		return $content;
	}

	$cta  = '<aside class="nahnu-cta">';
	$cta .= '<p class="nahnu-cta__title">Enjoyed this post?</p>';
	$cta .= '<p>Get new guides in your inbox once a month.</p>';
	$cta .= '<p><a class="wp-element-button" href="' . esc_url( home_url( '/newsletter/' ) ) . '">Subscribe</a></p>';
	$cta .= '</aside>';

	return $content . $cta;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

The end of a post is when readers are most engaged, so it’s the best place to ask them to do something next. This snippet adds one box to every post, and changing the snippet updates them all at once.

How it works

The snippet adds HTML to the end of the_content on single blog posts only. The checks for in_the_loop() and is_main_query() stop it appearing in sidebars, excerpts or related posts.

The button uses the wp-element-button class, so it picks up your theme’s button style.

Things to watch

  • To show a reusable block instead, replace the HTML with do_blocks( get_post( 123 )->post_content ) using the ID of a synced pattern.
  • Add styling for .nahnu-cta in your theme, for example a background colour and padding.

How to test it

View any blog post. The box should appear after the last paragraph.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only