Howto keep header image when changing theme

We have a setup where bloggers can and will have their theme changed. Is it possible to migrate the existing header image to the new theme ? I know how to override the header image with the add_filter, also know how to get the current header image. The issue here is to keep the header image when changing the theme. Is that possible ?

Related posts

Leave a Reply

3 comments

  1. Here comes the plugins to rescue, move that code into a plugin and activate. That’ll not change header image upon every theme change.

    E.g –

    <?php
    /*
    Plugin Name: keep header always
    */
    
    // Your code to keep header image
    
    ?>
    

    save it as whatever-foo.php upload to /wp-content/plugins/ directory and activate it

  2. The header image is set per …

    set_theme_mod( 'header_image', $choice['url'] )
    

    … a wrapper for …

    update_option( 'theme_mods_' . get_option( 'stylesheet' ), $value );
    

    So you can hook into …

    'pre_update_option_theme_mods_' . get_option( 'stylesheet' )
    

    … take the first parameter, which is an array of all theme mods, and save the value of the key 'header_image' in a plugin option. The key 'header_image_data' stores the meta data for that image.

    Then filter 'theme_mod_header_image' to return your stored plugin option if there is no image set.

  3. We did a small mu-plugin that solved our issue.

    Here is the code

    add_action('pre_update_option_stylesheet', 'phi_pre_update_option_stylesheet');
    add_action('switch_theme', 'phi_switch_theme');
    
    function phi_pre_update_option_stylesheet($stylesheet)
    {
        update_option('previous_header_image_saved', get_theme_mod('header_image'));
    
        return $stylesheet;
    }
    
    function phi_switch_theme()
    {
            if (get_option('previous_header_image_saved')) {
                    set_theme_mod('header_image', get_option('previous_header_image_saved'));
                delete_option('previous_header_image_saved');
        }
    }