Admin Bar (Toolbar) not showing on custom PHP file that loads WordPress

If WordPress is loaded from outside of the main WordPress files using a separate PHP script that includes wp-load.php then the /template-loader.php file will not be loaded and therefore the template_redirect action will not be triggered.

This is important because template_redirect is how the Toolbar is initialized on the front end. Taking a look at default-filters.php we can see where the Toolbar is initialized:

...
// Admin Bar
// Don't remove. Wrong way to disable.
add_action( 'template_redirect', '_wp_admin_bar_init', 0 ); // <-- initialize Toolbar
add_action( 'admin_init', '_wp_admin_bar_init' ); // <-- initialize Toolbar
add_action( 'before_signup_header', '_wp_admin_bar_init' ); // <-- initialize Toolbar
add_action( 'activate_header', '_wp_admin_bar_init' ); // <-- initialize Toolbar
add_action( 'wp_footer', 'wp_admin_bar_render', 1000 );
add_action( 'in_admin_header', 'wp_admin_bar_render', 0 );
...

A function can be added via plugin or theme to trigger the initialization of the Toolbar:

function wpse240134_wp_admin_bar_init() {
    _wp_admin_bar_init();
}
add_action( 'init', 'wpse240134_wp_admin_bar_init' );

Note that _wp_admin_bar_init() is considered an internal function for WordPress so use it at your own risk.

It’s also worth noting that if WordPress is being loaded from an external PHP file by including wp-blog-header.php and the WP_USE_THEMES constant is set to false, the template_redirect hook will again not be fired, so the wpse240134_wp_admin_bar_init() function above can be used to get the admin bar to show up when WP_USE_THEMES is set to false:

<?php
/**
 * Demonstration  of loading WordPress from an external PHP file.
 * 
 */
define('WP_USE_THEMES', false);

// https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files
//require ('./wp-load.php');

require ('./wp-blog-header.php');

?><!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="profile" href="http://gmpg.org/xfn/11">
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">

    <?php wp_head(); ?>
</head>

<body id="body" <?php body_class(); ?>>
    <div id="page" class="site">
        <header id="header" class="site-header"></header>

        <div id="content" class="site-content">
            <h1>Test of loading WordPress from external PHP file</h1>
        </div>

        <footer id="footer" class="site-footer"></footer>
    </div>
<?php wp_footer(); ?>
</body>
</html>

More details on loading WP using an external PHP file: What is the correct way to use wordpress functions outside wordpress files?

Leave a Comment