Show something on the frontpage only in WordPress using php if statements

September04, 2018
John Sheahan

One of the most common little jobs I come across during development of WordPress websites is how to show or hide an element (for example a slider, image etc) depending on whether you are visiting the homepage of the website or any of the inner pages.

There are several methods of doing this:


Using CSS

You could hide the element using CSS based on the pages ‘body’ class. For example if you wanted to hide the MetaSlider plugin on all pages bar the homepage you might use the following CSS in your stylesheet:



.metaslider {
display: none;   /* this tells the website to hide the slider everywhere */ 

}

.home .metaslider {
display: block  /* this tells the website to display the slider on homepage only as its using the home body class */

}

However, this is not an ideal solution as it means the slider is still there behind the scenes and loaded on each page. You just can’t see it because it is “hidden” using CSS.


Using a plugin

This is a better option than the CSS option above but still not ideal as it means installing another plugin on your website. The less plugins you have to use on your website, the better for optimal performance and less security risks.

A good plugin I use regularly however is Widget Options which allows you to show/hide plugins or widgets on a per-page basis. So you can show a slider widget on your homepage for example but not on any other page by simply selecting a checkbox in the widget.


The best method – Using PHP

Without doubt the cleanest and most effective method is using a simple PHP if statement. This ensures that the item on question only displays on the homepage and nowhere else.

So here it is:

<?php if(is_front_page() ) { ?>  

/* Paste your widget shortcode here or anything else such as an image or div */ 

 <?php } ?>

Hope that helps!