多选类别WordPress定制器控件

时间:2016-07-20 12:55:33

标签: php wordpress

我尝试创建一个多选框类别下拉列表,我遇到了问题。

以下是自定义控件类:

class Nt_Customize_Control_Multiple_Select extends WP_Customize_Control {

/**
 * The type of customize control being rendered.
 */
public $type = 'multiple-select';

/**
 * Displays the multiple select on the customize screen.
 */
public function render_content() {

if ( empty( $this->choices ) )
    return;
?>
    <label>
        <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
        <select <?php $this->link(); ?> multiple="multiple" style="height: 100%;">
            <?php
                foreach ( $this->choices as $value => $label ) {
                    $selected = ( in_array( $value, $this->value() ) ) ? selected( 1, 1, false ) : '';
                    echo '<option value="' . esc_attr( $value ) . '"' . $selected . '>' . $label . '</option>';
                }
            ?>
        </select>
    </label>
<?php }}

定制工具选项:

    $wp_customize->add_setting( 'nt_featured_cat', array(
    'default' => 0,
    'transport'   => 'refresh',
   'sanitize_callback' => 'nt_sanitize_cat' ));

$wp_customize->add_control(
    new Nt_Customize_Control_Multiple_Select (
        $wp_customize,
        'nt_featured_cat',
        array(
            'settings' => 'nt_featured_cat',
            'label'    => 'Featured category',
            'section'  => 'nt_blog_archive_section', // Enter the name of your own section
            'type'     => 'multiple-select', // The $type in our class
            'choices' => nt_cats()
        )
    )
);

和类别功能:

 function nt_cats() {
  $cats = array();
  $cats[0] = "All";
  foreach ( get_categories() as $categories => $category ) {
    $cats[$category->term_id] = $category->name;
  }
  return $cats;
}

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:2)

您已指定了清理功能nt_sanitize_cat,您是否定义了此功能?

$wp_customize->add_setting( 'nt_featured_cat', array(
    'default' => 0,
    'transport'   => 'refresh',
    'sanitize_callback' => 'nt_sanitize_cat' 
));

我实现了你的代码并添加了这个sanitize函数,我得到了一个返回值的数组:

/**
 * Validate the options against the existing categories
 * @param  string[] $input
 * @return string
 */
function nt_sanitize_cat( $input )
{
    $valid = nt_cats();

    foreach ($input as $value) {
        if ( !array_key_exists( $value, $valid ) ) {
            return [];
        }
    }

    return $input;
}