WordPress: Detect Homepage on Functions.php

Sometimes you may want to write code that triggers a hook in the homepage of your WordPress site. You try using this code:

// Wrong way if you want to use a hook
// DO NOT USE THIS
if ( is_home() || is_front_page() ) {
  // Add a hook (filter/action) here
}

It can not work because these functions can be really triggered in WordPress template files only. More specifically, they can only be triggered after the main WordPress query is run.

A simple workaround looks like this and actually it can apply to any site, not just WordPress:

// Correct way if you want to use a hook
if ( $_SERVER[ 'REQUEST_URI'] === '/' ) {
  // Add a hook (filter/action) here
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s