bghouse
bghouse

Reputation: 558

detecting if it's the home page in functions.php

I'm trying to detect if the current page is the home page in my fresh install of WordPress.

The snippet of code below works in page.php but it does not work in functions.php. How can i detect for the homepage in functions.php in WordPress?

if (is_front_page()) {
    echo 'test';
}

I know I can use $_SERVER['REQUEST_URI'], but I figured there should be a better way of doing this.

In the wordpress Settings > Reading, I have a static page for my home page. is_home() does not work in my page.php but is_front_page() does work in my page.php. Both these functions do not work in my functions.php

Upvotes: 5

Views: 15043

Answers (1)

Pieter Goosen
Pieter Goosen

Reputation: 9941

Simply use the is_home() conditional tag to check for homepage

EDIT

From your comments, what you are trying will never work. You need to add your code inside a function and then hook it to some hook

<?php
function my_custom_function() {
    if(is_front_page()){ 
        echo "home"; 
    }else{ 
        echo "not home"; 
    }
}
add_action( 'wp_head', 'my_custom_function' );

You are also stating in a comment that you want to load styles and scripts on the frontpage only. You can try the following

<?php
function my_custom_function() {
    if(is_front_page()){ 
       //Load your styles and scripts
    }
}
add_action( 'wp_enqueue_scripts', 'my_custom_function' );

Upvotes: 14

Related Questions