How to create a top bar through the customizer in WordPress

To create a top bar through the customizer in WordPress, you’ll need to use the WordPress Customizer API to add a new section, settings, and controls for the top bar. Below is an example code snippet that demonstrates how to add a customizable top bar:

First, you need to add the following code to your theme’s functions.php file:

// Add a new section to the Customizer
function theme_customizer_top_bar_section($wp_customize) {
    $wp_customize->add_section('top_bar_section', array(
        'title' => __('Top Bar', 'theme-textdomain'),
        'priority' => 30,
    ));
}

add_action('customize_register', 'theme_customizer_top_bar_section');

// Add setting for top bar text
function theme_customizer_top_bar_text_setting($wp_customize) {
    $wp_customize->add_setting('top_bar_text', array(
        'default' => '',
        'sanitize_callback' => 'sanitize_text_field',
    ));

    $wp_customize->add_control('top_bar_text', array(
        'type' => 'text',
        'label' => __('Top Bar Text', 'theme-textdomain'),
        'section' => 'top_bar_section',
    ));
}

add_action('customize_register', 'theme_customizer_top_bar_text_setting');

// Add setting for top bar background color
function theme_customizer_top_bar_bg_color_setting($wp_customize) {
    $wp_customize->add_setting('top_bar_bg_color', array(
        'default' => '#f5f5f5',
        'sanitize_callback' => 'sanitize_hex_color',
    ));

    $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'top_bar_bg_color', array(
        'label' => __('Top Bar Background Color', 'theme-textdomain'),
        'section' => 'top_bar_section',
    )));
}

add_action('customize_register', 'theme_customizer_top_bar_bg_color_setting');

Next, you need to display the top bar on your site using the added settings. For example, you can use the following code in your theme’s header.php or template file where you want the top bar to appear:

<?php
$top_bar_text = get_theme_mod('top_bar_text', '');
$top_bar_bg_color = get_theme_mod('top_bar_bg_color', '#f5f5f5');
?>

<div class="top-bar" style="background-color: <?php echo esc_attr($top_bar_bg_color); ?>">
    <div class="container">
        <p><?php echo esc_html($top_bar_text); ?></p>
    </div>
</div>

In the code above, we retrieve the values of the top bar text and background color from the customizer settings using get_theme_mod(). We then use this information to display the top bar with the specified text and background color.

Conclusion

Make sure to adjust the HTML and CSS in the example code to match your theme’s structure and styling. Additionally, you can add more settings to the top_bar_section section as needed, such as options for links, social icons, or other elements you want to include in the top bar.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top