wordpress functions.php to include different scripts and styles for two separate custom headers

I am working on a wordpress web application and would like to have 2 different header files that I can use depending on which section of the website i am on. For example display custom header#1 if not logged in and display custom header#2 if logged in. I want to enqueue different script and style files on each of the header files using the functions.php file. The problem is that i need call wp_head() on each of the header files which means that they will load the same scripts and files. Any suggestions would be appreciated.

Related posts

2 comments

  1. The WordPress’ get_header() function can be used to include a different header template by passing in a parameter. Example:

    // index.php
    get_header(); // Will include header.php.
    
    // some-template.php
    get_header('other'); // Will include header-other.php.
    

    This is the preferred way to do it when the header depends on template files. If you need to show different headers for logged in users for example, the following is a quick solution:

    if (is_user_logged_in()) :
        get_header(); // Includes header.php.
    else :
        get_header('guest'); // Includes header-guest.php.
    endif;
    

    To enqueue different scripts and styles to different templates and pages, you can just hook into the wp_enqueue_scripts hook and determine what to register and enqueue using WP conditionals:

    add_action('wp_enqueue_scripts', function () {
        wp_register_script('script-for-home', $urltoscript, ...);
        wp_register_script('script-for-page', $urltoscript, ...);
        wp_register_script('script-for-template', $urltoscript, ...);
    
        if (is_home()) {
            wp_enqueue_script('script-for-home');
        } elseif (is_page()) {
            wp_enqueue_script('script-for-page');
        } elseif (is_page_template('template.php')) {
            wp_enqueue_script('script-for-template');
        }
    });
    

    Conditional enqueues in wp-admin are a bit trickier, but look into wp_get_current_screen to check the current admin page.

  2. function wpd_enqueue_scripts() {
        if( is_user_logged_in() ){
            wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/logged-in.js', array(), '1.0.0', true );
     wp_enqueue_style( 'twentythirteen-bootstrap.min', get_template_directory_uri() . '/css/bootstrap.min.css', array(), 'v3.1.0' );
        } else {
            wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/not-logged-in.js', array(), '1.0.0', true );
     wp_enqueue_style( 'twentythirteen-bootstrap.min', get_template_directory_uri() . '/css/bootstrap.min1.css', array(), 'v3.1.0' );
        }
    }
    add_action( 'wp_enqueue_scripts', 'wpd_enqueue_scripts' );
    

Comments are closed.