How can I add a custom header to a custom template in a plugin without using the theme folders

The get_header() functions is designed for themes. It usually look for header file in child theme first and then parent theme. You should be creating custom header under theme directory instead of in a plugin.

But if you really must have to load header file from plugin then you have to create a custom function.

Here is how you can do it.

Create a file header-custom.php in your plugin:

<?php
/**
 * PLUGIN_DIR/includes/header-custom.php
 * Header file in plugin
 */

?><!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="https://gmpg.org/xfn/11">

        <?php wp_head(); ?>

    </head>

    <body <?php body_class(); ?>>
?>

Create custom function _get_header() which will first look for file in your plugin and then child theme and then parent theme. Change the values in below function according to your need. e.g. Plugin path

function _get_header($name, $args = array()) {

    $require_once = true;
    $templates = array();

    $name = (string) $name;
    if ('' !== $name) {
        $templates[] = "header-{$name}.php";
    } else {
        return false;
    }

    $templates[] = 'header.php';

    $located = '';
    foreach ($templates as $template_name) {

        if (!$template_name) {
            continue;
        }

        if (file_exists(WP_PLUGIN_DIR . '/PLUGIN_DIR/includes/' . $template_name)) {

            $located = WP_PLUGIN_DIR . '/PLUGIN_DIR/includes/' . $template_name;
            break;
        } elseif (file_exists(STYLESHEETPATH . "https://wordpress.stackexchange.com/" . $template_name)) {
            $located = STYLESHEETPATH . "https://wordpress.stackexchange.com/" . $template_name;
            break;
        } elseif (file_exists(TEMPLATEPATH . "https://wordpress.stackexchange.com/" . $template_name)) {
            $located = TEMPLATEPATH . "https://wordpress.stackexchange.com/" . $template_name;
            break;
        } elseif (file_exists(ABSPATH . WPINC . '/theme-compat/' . $template_name)) {
            $located = ABSPATH . WPINC . '/theme-compat/' . $template_name;
            break;
        }
    }

    if ('' !== $located) {
        load_template($located, $require_once, $args);
    }

    return $located;
}

And then in your regular theme file you can add _get_header() function like this:

// Check if plugin is active then load file from plugin
if(in_array('PLUGIN_DIR/PLUGIN.php', apply_filters('active_plugins', get_option('active_plugins')))){ 
    _get_header('custom'); //loads header-custom.php from plugin 

} else {
    get_header();
}

Leave a Comment