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 comment