Using WordPress ‘get_header’ PHP action

The get_header WordPress PHP action fires before the header template file is loaded.

Usage

add_action('get_header', 'your_custom_function_name');
function your_custom_function_name($name) {
    // your custom code here
}

Parameters

  • $name (string|null) – Name of the specific header file to use. Null for the default header.
  • $args (array) – Additional arguments passed to the header template.

More information

See WordPress Developer Resources: get_header

Examples

Change Header Based on Page Template

Change the header file based on the current page’s template.

add_action('get_header', 'custom_header_based_on_page_template');
function custom_header_based_on_page_template($name) {
    if (is_page_template('template-about.php')) {
        $name = 'about';
    }
    return $name;
}

Add Custom CSS Class to Body

Add a custom CSS class to the body element for specific header files.

add_action('get_header', 'custom_css_class_for_header');
function custom_css_class_for_header($name) {
    if ($name == 'custom-header') {
        add_filter('body_class', 'add_custom_body_class');
    }
}

function add_custom_body_class($classes) {
    $classes[] = 'custom-header-class';
    return $classes;
}

Load Custom JavaScript for Specific Header

Load custom JavaScript file when using a specific header.

add_action('get_header', 'load_custom_js_for_header');
function load_custom_js_for_header($name) {
    if ($name == 'custom-header') {
        wp_enqueue_script('custom-header-js', get_template_directory_uri() . '/js/custom-header.js', array(), '1.0.0', true);
    }
}

Modify Site Title for a Specific Header

Change the site title when using a specific header.

add_action('get_header', 'modify_site_title_for_header');
function modify_site_title_for_header($name) {
    if ($name == 'custom-header') {
        add_filter('pre_get_document_title', 'change_site_title');
    }
}

function change_site_title($title) {
    return 'Custom Site Title';
}

Add Custom Header Template for Single Posts

Use a custom header for single posts.

add_action('get_header', 'custom_header_for_single_posts');
function custom_header_for_single_posts($name) {
    if (is_single()) {
        $name = 'single-post';
    }
    return $name;
}