2016-07-20 48 views
1

我试图创建一个多选框类别下拉,即时通讯有问题。多选择类别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; 
} 

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

+0

什么是您所遇到的问题?你有错误吗? –

+0

@AndrewMyers我用'WP_Query'做了一个循环,类别不打印任何东西,'var_dump'返回'STRING''(LENGTH = 0)' – HiroHito

回答

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; 
}