3

我有一个使用定制主题的 Wordpress 网站。我想在管理员的某处添加一个功能切换(复选框设置),各个主题页面可以读取它以更改它们的行为。

实现这一点的最佳方法是什么?如果您可以包括我如何阅读该设置,将不胜感激。

4

1 回答 1

4

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

这进入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;
?>

结果是:

于 2014-07-05T11:27:30.157 回答