默认情况下在WordPress小工具中启用复选框

时间:2016-03-30 作者:webvitaly

代码按预期工作。

如果我默认设置“show\\u post\\u count”=>1,则会出现此问题。在这种情况下,复选框将始终启用。

即使复选框值默认设置为1,我也应该如何更新代码以使其按预期工作。

<?php

class Custom_Archives_Widget extends WP_Widget {

    /**
     * Register widget with WordPress.
     */
    function __construct() {
        parent::__construct(
            \'custom_archives_widget\', // Base ID
            __( \'Custom Archives\', \'custom\' ), // Name
            array( \'description\' => __( \'Custom Archives Widget\', \'custom\' ) ) // Args
        );
    }


    /**
     * Front-end display of widget.
     *
     * @see WP_Widget::widget()
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {
        //extract( $args );
        $instance = wp_parse_args( (array) $instance, self::get_defaults() );

        echo $args[\'before_widget\'];

        if ( ! empty( $instance[\'title\'] ) ) {
            echo $args[\'before_title\'] . apply_filters( \'widget_title\', $instance[\'title\'] ). $args[\'after_title\'];
        }

        $instance[\'echo\'] = false;
        $archives = wp_get_archives( $instance );

        if ( $instance[\'format\'] == \'option\' ) { // Archives as a dropdown

            echo \'<p class="custom-archives"><select name="archive-dropdown" onchange=\\\'document.location.href=this.options[this.selectedIndex].value;\\\'>\';
                echo \'<option value=""></option>\';
                echo $archives;
            echo \'</select></p><!-- .custom-archives -->\';

        } elseif ( $instance[\'format\'] == \'html\' ) { // Archives as an unordered list

            echo \'<ul class="custom-archives">\' . $archives . \'</ul><!-- .custom-archives -->\';

        } else { // Other formats

            echo $archives;

        }
        echo $args[\'after_widget\'];
    }


    /**
     * Back-end widget form.
     *
     * @see WP_Widget::form()
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        $instance = wp_parse_args( (array) $instance, self::get_defaults() );

        $type_list = array( 
            \'yearly\' => __( \'Yearly\', \'custom\' ),
            \'monthly\' => __( \'Monthly\', \'custom\' ),
            \'daily\' => __( \'Daily\', \'custom\' ),
            \'weekly\' => __( \'Weekly\', \'custom\' ),
            \'postbypost\' => __( \'Post By Post\', \'custom\' ),
            \'alpha\' => __( \'Alphabetical\', \'custom\' )
        );

        $format_list = array(
            \'html\' => __( \'HTML\', \'custom\' ),
            \'option\' => __( \'Dropdown\', \'custom\' ),
            \'custom\' => __( \'Custom\', \'custom\' )
        );

        $order_list = array(
            \'ASC\'  => __( \'Ascending (A-Z)\', \'custom\' ),
            \'DESC\' => __( \'Descending (Z-A)\', \'custom\' )
        );

        ?>
<p>
    <label><?php _e( \'Title:\', \'custom\' ); ?><br>
        <input type="text" class="widefat" name="<?php echo $this->get_field_name( \'title\' ); ?>" 
            value="<?php echo esc_attr( $instance[\'title\'] ); ?>">
    </label>
</p>

<p>
    <label><?php _e( \'Type:\', \'custom\' ); ?><br>
        <select class="widefat" name="<?php echo $this->get_field_name( \'type\' ); ?>">
            <?php foreach ( $type_list as $option_value => $option_label ) { ?>
                <option value="<?php echo esc_attr( $option_value ); ?>" <?php selected( $instance[\'type\'], $option_value ); ?>><?php echo esc_html( $option_label ); ?></option>
            <?php } ?>
        </select>
    </label>
</p>

<p>
    <label><?php _e( \'Limit:\', \'custom\' ); ?><br>
        <input type="number" class="widefat" min="0" name="<?php echo $this->get_field_name( \'limit\' ); ?>" 
            value="<?php echo esc_attr( $instance[\'limit\'] ); ?>" />
    </label>
</p>

<p>
    <label><?php _e( \'Format:\', \'custom\' ); ?><br>
        <select class="widefat" name="<?php echo $this->get_field_name( \'format\' ); ?>">
            <?php foreach ( $format_list as $option_value => $option_label ) { ?>
                <option value="<?php echo esc_attr( $option_value ); ?>" <?php selected( $instance[\'format\'], $option_value ); ?>><?php echo esc_html( $option_label ); ?></option>
            <?php } ?>
        </select>
    </label>
</p>

<p>
    <label>
        <input class="checkbox" type="checkbox" <?php checked( $instance[\'show_post_count\'] ); ?> 
            name="<?php echo $this->get_field_name( \'show_post_count\' ); ?>" />
        <?php _e( \'Show post count\', \'custom\' ); ?>
    </label>
</p>

<p>
    <label><?php _e( \'Order:\', \'custom\' ); ?><br>
        <select class="widefat" name="<?php echo $this->get_field_name( \'order\' ); ?>">
            <?php foreach ( $order_list as $option_value => $option_label ) { ?>
                <option value="<?php echo esc_attr( $option_value ); ?>" <?php selected( $instance[\'order\'], $option_value ); ?>><?php echo esc_html( $option_label ); ?></option>
            <?php } ?>
        </select>
    </label>
</p>
        <?php 
    }


    /**
     * Sanitize widget form values as they are saved.
     *
     * @see WP_Widget::update()
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = $old_instance;
        $new_instance = wp_parse_args( (array) $new_instance, self::get_defaults() );
        $instance[\'title\'] = trim(strip_tags($new_instance[\'title\']));
        $instance[\'type\'] = $new_instance[\'type\'];
        $instance[\'limit\'] = intval( $new_instance[\'limit\'] );
        $instance[\'limit\'] = $instance[\'limit\'] === 0 ? \'\' : $instance[\'limit\'];
        $instance[\'format\'] = $new_instance[\'format\'];

        $instance[\'show_post_count\'] = $new_instance[\'show_post_count\'] ? 1 : 0;

        /*$instance[\'show_post_count\'] = 1;
        if( !isset( $new_instance[\'show_post_count\'] ) || empty( $new_instance[\'show_post_count\'] ) ) {
            $instance[\'show_post_count\'] = 0;
        }*/

        $instance[\'order\'] = $new_instance[\'order\'];
        return $instance;
    }


    /**
     * Render an array of default values.
     *
     * @return array default values
     */
    private static function get_defaults() {
        $defaults = array(
            \'title\' => __( \'Archives\', \'custom\' ),
            \'description\' => \'\',
            \'type\' => \'monthly\',
            \'limit\' => 10,
            \'format\' => \'html\',
            \'show_post_count\' => 0,
            \'order\' => \'DESC\'
        );
        return $defaults;
    }

}


function custom_archives_register_widget() {
    register_widget( \'Custom_Archives_Widget\' );
}
add_action( \'widgets_init\', \'custom_archives_register_widget\' );

1 个回复
最合适的回答,由SO网友:Sumit 整理而成

Please note 如果未选中复选框,则key 未在过帐表单数据中设置。所以当你取消选中show_post_count, 发布的数组没有此键,并且update() 您正在使用默认值对其进行解析的函数。

$new_instance = wp_parse_args( (array) $new_instance, self::get_defaults() );
因此$instance[\'show_post_count\'] 将会有1 即使取消选中,也始终如此。

解决方案:

请优先考虑用户输入,如果缺少某些内容,请使用默认参数填充。更新后的函数如下所示!

public function update( $new_instance, $instance ) {
    $instance[\'title\'] = trim(strip_tags($new_instance[\'title\']));
    $instance[\'type\'] = $new_instance[\'type\'];
    $instance[\'limit\'] = intval( $new_instance[\'limit\'] );
    $instance[\'limit\'] = $instance[\'limit\'] === 0 ? \'\' : $instance[\'limit\'];
    $instance[\'format\'] = $new_instance[\'format\'];
    //Add isset to check if key is set!
    $instance[\'show_post_count\'] = isset($new_instance[\'show_post_count\']) ? 1 : 0;
    $instance[\'order\'] = $new_instance[\'order\'];

    //Fill with default value if any key is missing!
    $updated_instance = wp_parse_args( (array) $instance, self::get_defaults() );

    return $updated_instance;
}

相关推荐

My widgets do not save

每次我保存我的小部件并离开页面时,我的小部件都会消失。侧边栏已完全清空,不会保存任何更改。控制台或PHP日志中没有任何错误。如果我将小部件直接复制并保存在数据库中widgets_text, 它们将被显示,但我仍然无法在侧边栏中添加或删除任何内容。这只发生在我的右侧边栏上,左侧边栏工作正常,但它们都以相同的方式注册。这是我注册侧边栏的方式:function my_widgets_init() { register_sidebar( array ( \'name\'