Hook to get the page template that is in use on the admin page edit screen?

I would like to find out which page template is in use as I only want to enqueue some javascript if the page is using a certain template. Is this possible?

3 Answers
3

I’m not sure if this is for front end or back end, so I’m going to handle both.

BACK END

You can make use of get_current_screen() or the $pagenow global. Here are two examples which you can add in a plugin or in your functions.php to check the relevant info on an admin page

add_action( 'current_screen', function ( $current_screen )
{
    ?><pre><?php var_dump($current_screen); ?></pre><?php   

});

and

add_action( 'admin_head', function ()
{
    global $pagenow;

    ?><pre><?php var_dump($pagenow); ?></pre><?php  

});

Once you have the name of the specific admin page, you can do the following

add_action( 'admin_enqueue_scripts', function ( $hook ) 
{
    if ( 'some-page.php' === $hook ) {
        // Add your scripts
    }
});

FRONT END

As birgire pointed out, if you need to know this on front end, you can simply test this with is_page_template( 'some-template.php' )

add_action( 'wp_enqueue_scripts', function ()
{
    if ( is_page_template( 'some-template.php' ) ) {
        // Enqueue your script
    }
});

Leave a Comment