Performance: Theme customizer
Theme customizer affects page load speed and rendering performance by dynamically applying style and layout changes during preview.
Jump into concepts and practice - no test required
function mytheme_customize_register($wp_customize) {
$wp_customize->add_setting('background_color', array('default' => '#ffffff', 'transport' => 'postMessage'));
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'background_color_control', array(
'label' => 'Background Color',
'section' => 'colors',
'settings' => 'background_color',
)));
}
function mytheme_customize_preview_js() {
wp_enqueue_script('mytheme-customizer', get_template_directory_uri() . '/js/customizer.js', array('customize-preview'), null, true);
}
add_action('customize_preview_init', 'mytheme_customize_preview_js');function mytheme_customize_register($wp_customize) {
$wp_customize->add_setting('background_color', array('default' => '#ffffff'));
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'background_color_control', array(
'label' => 'Background Color',
'section' => 'colors',
'settings' => 'background_color',
)));
add_action('wp_head', function() {
echo '<style>body { background-color: ' . get_theme_mod('background_color') . '; }</style>';
});
}
add_action('customize_register', 'mytheme_customize_register');| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| PHP inline style injection | Minimal DOM nodes | Triggers 1 reflow per page load | Medium paint cost due to style recalculation | [X] Bad |
| JavaScript postMessage live preview | Minimal DOM nodes | No reflows triggered on preview update | Low paint cost, only updates changed styles | [OK] Good |
add_section() is specifically used to add a new section in the Theme Customizer.add_setting() adds settings, add_control() adds controls, and register_section() is not a valid function. $wp_customize->add_setting('header_text', [
'default' => 'Welcome!',
'sanitize_callback' => 'sanitize_text_field'
]);
$wp_customize->add_control('header_text', [
'label' => 'Header Text',
'section' => 'title_tagline',
'type' => 'text'
]);
What will get_theme_mod('header_text') return if the user has not changed the setting?get_theme_mod() returns the default value. $wp_customize->add_setting('footer_text', [
'default' => 'Footer here',
'sanitize_callback' => 'sanitize_text_field'
]);
$wp_customize->add_control('footer_text', [
'label' => 'Footer Text',
'section' => 'footer_section',
'type' => 'textarea'
]);
Assuming 'footer_section' was never added, what issue will occur?add_section() to group background options.add_setting() to define the background color setting and provide a default value.add_control() with type => 'color' to let users pick a color.