Show a message only on the front page

Description: Print the text Welcome to our site! at the end of the home page only. The text must not show on posts or pages.

Hint:

  • Use the wp_footer action and the conditional tag is_front_page().

Solution

<?php
add_action( 'wp_footer', function () {
	if ( is_front_page() ) {
		echo '<p class="welcome">Welcome to our site!</p>';
	}
} );
Terminal output

$ curl -s http://example.com/ | grep -o '<p class="welcome">[^<]*</p>'
<p class="welcome">Welcome to our site!</p>
$ curl -s http://example.com/hello-world/ | grep -c 'class="welcome"'
0

How it works

  • The function is attached to wp_footer, which runs on every front page.
  • is_front_page() is true only on the front page, so the message is missing on the post (the count is 0).

Read Conditional Tags.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.