Adding a global setting (feature toggle) to Wordpress

二次信任 提交于 2019-12-07 15:55:30

问题


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.


回答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:



来源:https://stackoverflow.com/questions/24523182/adding-a-global-setting-feature-toggle-to-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!