Adding a global setting (feature toggle) to WordPress

I have a WordPress site that uses a bespoke theme. I’d like to add a feature toggle (checkbox setting) somewhere in the admin that can be read by the various theme pages to change their behavior.

What’s the best way to implement this? If you could include how I could then read that setting, it would be appreciated.

Related posts

Leave a Reply

1 comment

  1. Use the Theme Customization API for that. A checkbox is not within the default controls, so a custom control has to be built.

    This goes in functions.php:

    /**
     * Custom controller
     * See http://ottopress.com/2012/making-a-custom-control-for-the-theme-customizer/
     */
    if ( class_exists('WP_Customize_Control') ) {
        class Example_Customize_Textarea_Control extends WP_Customize_Control {
            public $type = 'checkbox';
    
            public function render_content() {
                ?>
                <label>
                <span class="customize-control-select"><?php echo esc_html( $this->label ); ?></span>
                <input <?php $this->link(); ?> type="checkbox" value="1" class="code" <?php checked( 1, $this->value() ); ?> />
                </label>
                <?php
            }
        }
    }
    
    /**
     * Add custom theme options
     */
    function theme_options_so_24523182( $wp_customize ) {
        $wp_customize->add_section(
                'bespoke_settings',
                array(
                 'title' => 'Bespoke',
                 'description' => 'My custom settings',
                 'priority' => 11
                )
            );
            $wp_customize->add_setting( 
                'show_header', 
                array(
                    'default' => false,
                )
            );
            $wp_customize->add_control( new Example_Customize_Textarea_Control( 
                $wp_customize, 
                'show_header', 
                array(
                    'label'   => 'Show header',
                    'section' => 'bespoke_settings',
                    'settings'   => 'show_header',
                    'priority' => 8
                ) 
            ));
    }
    add_action( 'customize_register', 'theme_options_so_24523182' );
    

    And in header.php:

    <?php
        $show = get_theme_mod( 'show_header' );
        if( $show ):
            echo "Hello, world!";
        endif;
    ?>
    

    Results in: