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
WordPress Themes
WordPress Top Theme List
WordPress Theme Files and Functions
WordPress Template Hierarchy
WordPress Enqueue Scripts and Styles
WordPress Loop
WordPress WP_Query Class
Exercises & Assignments
Build and activate a minimal classic theme
Show the three latest posts with WP_Query
Load a stylesheet with wp_enqueue_style and a version
Show a message only on the front page
Create a child theme which changes the footer
Interview Questions & Answers
What is a WordPress theme?
What are commonly used WordPress theme functions?
Which function is used to get the home URL in WordPress?
Which are the necessary files for a WordPress theme?
What is the use of the wp_head() function in WordPress?
What is the WordPress Loop?
What is the difference between is_home() and is_front_page()?