首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多选类别WordPress定制器控件

多选类别WordPress定制器控件
EN

Stack Overflow用户
提问于 2016-07-20 20:55:33
回答 1查看 1.6K关注 0票数 1

我正在尝试创建一个多选框类别下拉列表,我对它有一个问题。

下面是自定义控件类:

代码语言:javascript
复制
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 }}

定制器选项:

代码语言:javascript
复制
    $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()
        )
    )
);

类别的功能如下:

代码语言:javascript
复制
 function nt_cats() {
  $cats = array();
  $cats[0] = "All";
  foreach ( get_categories() as $categories => $category ) {
    $cats[$category->term_id] = $category->name;
  }
  return $cats;
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-24 20:41:27

您已经指定了一个清理函数nt_sanitize_cat,您是否定义了此函数?

代码语言:javascript
复制
$wp_customize->add_setting( 'nt_featured_cat', array(
    'default' => 0,
    'transport'   => 'refresh',
    'sanitize_callback' => 'nt_sanitize_cat' 
));

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

代码语言:javascript
复制
/**
 * 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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38481936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档