How do I make my child theme re-apply the settings that were customised when its parent was active?

I gave a +1 to the @webtoure’s answer because it gives you the right direction, however I think it lacks some checks.

First of all it does not check that the theme that’s being activated is a child theme, and does not check that the theme previously active is the parent theme of the child theme being activated.

Per my understanding of OP these conditions are required.

Moreover, one issue that you need to take into account is what to do with the theme mods of the child theme being activated, if they already exist.

In @webtoure answer, they are stored in a backup, that might save you under some circumstances, but WordPress will not recognize them by default and so they require some additional code to be used.

I think it would be better, to inherit the theme modifications from parent theme only the first time a child theme is activated.

In short, the conditions I want to check before to inherit theme mods from parent theme are:

  • the previously active theme must be the parent of the child theme that is being activated
  • the child theme that is being activated has to never been activated before

To ensure the second condition I’ll use a custom option, because WordPress does not provide a way to do this check.

This is the code, please read inline comments for explanation of what is going on:

add_action( 'switch_theme', function( $new_name, \WP_Theme $new_theme ) {

    // get the previously active theme
    $previous = get_option( 'theme_switched', -1 );

    // get the parent of current theme, will be false if no parent
    $parent = $new_theme->parent() ? $new_theme->get_template() : false;

    // current stylesheet name
    $stylesheet = get_option( 'stylesheet' );

    // has the theme being activated ever been activated before?
    $lastActive = get_option( $stylesheet . '_last_active', false );

    // if previouly active theme is the parent of the the child theme being activated
    // and it has never been activated before..
    if ( ! $lastActive && $parent === $previous ) {

        // update "last_active" option so following code won't run again for this theme
        update_option( $stylesheet . '_last_active', current_time( 'timestamp', 1 ) );

        // get the theme mods of the parent
        $previousMods = get_option( 'theme_mods_' . $parent, array() );

        // inherit current theme mods from parent theme mods
        update_option( 'theme_mods_' . $stylesheet, $previousMods );
    }

}, 10, 2 );

Leave a Comment