Add action hook conditionally – only when home.php in use

I am trying to add action hook in functions.php only if the page is home.php but the following does not work

if ( is_page_template("home.php") ) {

// do stuff

}

To make sure that file being used is home.php I do this

global $template; echo $template; 

Related posts

Leave a Reply

3 comments

  1. Use is_home instead, as is_page_template will not work for home.php as its technically not a page template in the traditional sense.

    add_action('template_redirect', 'are_we_home_yet', 10);
    function are_we_home_yet(){
            if ( is_home() ) {
            //your logic here
        }
    }
    

    Revised:

    add_action('template_redirect', 'are_we_home_yet', 10);
    function are_we_home_yet(){
            global $template;
            $template_file = basename((__FILE__).$template);
            if ( is_home() && $template_file = 'home.php' ) {
            //do your logic here
        }
    }
    

    The revised answer is actually what you really need, it will check if you are on the home page, in addition to getting the template file being included and check to see if that file is in fact your home.php file and if so, you can go about your logic…

  2. I’ve had this problem. I wanted to include Jssor Slider scripts only when loading the home page. I was using a home.php too, and I’ve solved it this way:

    1. Renamed my home.php file to something else, like home_mysite.php setting a name for this page template at the file’s top comment header, like:
    /**
    * Template Name: Home
    */
    
    1. Then I created a new empty page setting Home as page template.
    2. Configured WordPress to show my brand new page as front page (Settings > Reading > A static page > Front page: Home)
    3. Then, finally I figured out that it was necessary to put the conditional code inside my function for is_page('home') to work. (‘home’ is my empty new home page slug). That is, when I was trying to conditionally add the action, I wasn’t able to verify if my home page was loading, is_page('home') always returned false. It worked when I changed the logic for always adding the action but conditionally enqueuing the scripts.

    The code that worked out on functions.php:

    function mysite_jssor() {
        //conditionally enqueue the script 
        if ( is_page('home') ) {
            wp_enqueue_script( 'jssor', get_stylesheet_directory_uri() . '/js/jssor.js', array( 'jquery' ), false, false );
        }
    }
    //always adds the action
    add_action( 'wp_enqueue_scripts', 'mysite_jssor' );
    

    This way my Jssor scripts are loaded only when acessing the home page, not when acessing other pages or posts.

  3. The function you are looking for is is_front_page()

    add_action('template_redirect', 'work_only_on_front_page', 10);
       function work_only_on_front_page(){
        if ( is_front_page() ) {
        // Your code
       }
    }