2015-01-21 144 views
0

我有一個PHP函數返回PHP列表()格式的值。該函數返回一個WordPress分類法列表,其中包含手動添加的一些自定義條目。如何使用和訪問保存的數組值

/** 
* Returns array with taxonomies 
*/ 
public function get_taxonomies(){ 
    $args = array(
     'public' => true, 
     '_builtin' => false 
    ); 
    $taxonomies = get_taxonomies($args, 'objects'); 
    $list = array(); 
    $list[__('Category', $this->prefix)] = 'category'; 
    $list[__('Tag', $this->prefix)] = 'post_tag'; 
    foreach($taxonomies as $tax){ 

     $list[$tax->labels->name] = $tax->name; 
    } 
    return $list; 
} 

該函數返回以下數組值:

Array 
(
    [Category] => category 
    [Tag] => post_tag 
    [Product Categories] => product_cat 
    [Product Tags] => product_tag 
    [Shipping Classes] => product_shipping_class 
) 

陣列的第一部分是該分類名和第二分類法值。

我將這些值顯示爲複選框列表,並將它們作爲數組保存在我的數據庫中。

這是我保存在數據庫中的複選框列表的數據。這是返回什麼,如果我的print_r()保存數據列表:

Array 
(
    [category] => category 
    [post_tag] => post_tag 
    [product_cat] => product_cat 
) 

使用WordPress的檢查()函數我試圖返回分類與保存在標記爲數據庫中的值的初始列表HTML「已選中」。

這是我曾嘗試:

// This is where I am trying to get at the saved values 
$multi_stored = $options[$id]; 

$taxonomies = $this->get_taxonomies(); 
foreach($taxonomies as $name => $label){ 

    $check_key = $id . '_' . $option; 

    $output .= '<input class="checkbox'.$field_class.'" type="checkbox" name="'.$this->prefix.'_options['.$id.']['.$label.']" id="'.$check_key.'" value="'.$label.'" '.checked($multi_stored[$label], $label, false).' /><label for="'.esc_attr($name).'">'.esc_html($name).'</label><br />'; 
} 

當我運行此代碼,我收到了以下PHP警告。

注意:未定義指數:product_tag在C:\ XAMPP \ htdocs中\ wpbp-admin.php的就行...

它給我這個警告的每個項目的複選框不被選中的列表。

我想代碼不會返回這些警告。我知道這是使用isset的問題,但我不確定將它放在哪裏。

任何幫助非常感謝,謝謝。

回答

0

我得到它的工作。

我更改環路「檢查」功能,此:

$multi_stored = $options[$id]; 

$taxonomies = $this->get_taxonomies(); 
foreach($taxonomies as $name => $label){ 

    if(isset($multi_stored[$label])){ 
     if($label == $multi_stored[$label]){ 
      $checked = 'checked="checked"'; 
     } else { 
      $checked = ''; 
     } 
    } else { 
     $checked = ''; 
    } 

    $check_key = $id . '_' . $label; 

    $output .= '<input class="checkbox'.$field_class.'" type="checkbox" name="'.$this->prefix.'_options['.$id.']['.$label.']" id="'.$check_key.'" value="'.$label.'" '.$checked.' /><label for="'.esc_attr($name).'">'.esc_html($name).'</label><br />'; 
}