wordpressthemesget-headers

Switch Between Multiple Headers in WordPress Theme


I am building a custom theme for WordPress. One thing I want to do is allow myself to switch the header from the edit page.

I know I can hard code in the header to switch based on the page ID or name, like this:

<?php 
if(is_page(10)) {
 get_header('new');
}
else {
 get_header();
}
 wp_head();
?>

But I want a drop down menu similar to the Page Template option in the sidebar. (See screenshot)

Screenshot of sidebar menu

I have looked for any online tutorials that cover this type of option, but they all cover the basic ID or name setup shown above.

Does anyone know of a good tutorial to create a drop down similar to Page Templates to use for multiple headers?


Solution

  • You can use Custom Metaboxes. That link contains a comprehensive tutorial on creating custom metaboxes for post meta fields by hand. You can also use a plugin like Advanced Custom Fields to create them.

    Doing this would allow you to check for the header style value through get_post_meta() or get_field(), respectively.

    <?php
        // If using the Custom Metabox/post_meta approach:
        $header_style = get_post_meta( get_the_ID(), 'my_custom_header', true );
    
        // If using ACF:
        $header_style = get_field( 'my_custom_header', get_the_ID() );
    
        if( $header_style == 'new' ){
            get_header('new');
        if( $header_style == 'something-else' ){
            get_header('something-else');
        } else {
            get_header();
        }
    ?>