向 Wordpress 添加全局设置(功能切换) [英] Adding a global setting (feature toggle) to Wordpress

查看:36
本文介绍了向 Wordpress 添加全局设置(功能切换)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用定制主题的 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.

推荐答案

使用 主题自定义 API为了那个原因.复选框不在默认控件中,因此 必须构建自定义控件.

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

这在 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' );

header.php 中:

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

结果:

这篇关于向 Wordpress 添加全局设置(功能切换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆