Skip to content

Instantly share code, notes, and snippets.

@fastlinemedia
Last active August 11, 2020 10:44
Show Gist options
  • Save fastlinemedia/9a8070b9a636e38b510f to your computer and use it in GitHub Desktop.
Save fastlinemedia/9a8070b9a636e38b510f to your computer and use it in GitHub Desktop.
Import WordPress Customizer settings when a theme is activated.
/**
* This function assumes you have a Customizer export file in your theme directory
* at 'data/customizer.dat'. That file must be created using the Customizer Export/Import
* plugin found here... https://wordpress.org/plugins/customizer-export-import/
*/
function import_customizer_settings()
{
// Check to see if the settings have already been imported.
$template = get_template();
$imported = get_option( $template . '_customizer_import', false );
// Bail if already imported.
if ( $imported ) {
return;
}
// Get the path to the customizer export file.
$path = trailingslashit( get_stylesheet_directory() ) . 'data/customizer.dat';
// Return if the file doesn't exist.
if ( ! file_exists( $path ) ) {
return;
}
// Get the settings data.
$data = @unserialize( file_get_contents( $path ) );
// Return if something is wrong with the data.
if ( 'array' != gettype( $data ) || ! isset( $data['mods'] ) ) {
return;
}
// Import options.
if ( isset( $data['options'] ) ) {
foreach ( $data['options'] as $option_key => $option_value ) {
update_option( $option_key, $option_value );
}
}
// Import mods.
foreach ( $data['mods'] as $key => $val ) {
set_theme_mod( $key, $val );
}
// Set the option so we know these have already been imported.
set_option( $template . '_customizer_import', true );
}
add_action( 'after_switch_theme', 'import_customizer_settings' );
@cogdog
Copy link

cogdog commented Aug 6, 2018

Thanks for this code, it's helping on a current project - FYI error in line 46, the function to call is update_option not set_option

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment