我在WordPress插件中使用select2。基本目的是选择多个值。我可以选择多个值并将它们保存在数据库中。问题出在编辑页面上。它不显示所选选项。但在视图源模式中,所选选项已选择属性。
<select name="course_info_meta[campus_id][]" id="campus_id"
class="regular-text select2-hidden-accessible" multiple="" tabindex="-1" aria-hidden="true">
<optgroup label="Multan College of Science">
<option value="16"> Johar Campus </option>
<option value="11" selected="selected"> MCH Boys Branch </option>
<option value="13" selected="selected"> MCH Girls Branch </option>
</optgroup>
<optgroup></optgroup>
<optgroup label="Jalal Pur Public School">
<option value="14"> Boys Campus </option>
<option value="15" selected="selected"> JPPS Shuja Abad Campus </option>
</optgroup>
<optgroup> </optgroup>
</select>
jQuery就在这里
jQuery(function($) {
// Select2 dropdown for campuses
$('#campus_id').select2({
placeholder: 'Select a Campus',
'multiple': true,
closeOnSelect: false,
});
});
php代码
public function getAllCampusesList() {
$results = $this->getAllCampusesData();
foreach ($results as $key => $school) {
$school_name = $this->getSchoolNameById($key);
echo "<optgroup label='".$school_name."'>";
foreach ($school as $campus){
echo "<option value='".$campus['id']."' ".$this->selected_campus($campus['id'])."> ".$campus['name']." </option>";
} //level_2
echo "<optgroup>";
} //level_1
}
private function getAllCampusesData() {
$transient = PMS_Management::PLUGIN_SLUG . '_campus_list';
//delete_transient($transient);
if ( false === ( $ret = get_transient( $transient ) ) ) {
global $wpdb;
$query = "SELECT id,slug FROM `{$wpdb->pms_schools}`";
$results = $wpdb->get_results($query,ARRAY_A);
$ret = array();
if ( !empty( $results ) ):
foreach ( $results as $row ):
$slug = PMS_Management::PLUGIN_SLUG . '_' . $row['slug'];
$args = array(
'orderby' => 'date',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'hierarchical' => false,
);
$terms = get_terms( $slug, $args );
if( !is_wp_error( $terms ) && is_array( $terms ) ):
foreach ( $terms as $term ) {
$semester = array (
'id' => $term->term_id,
'name' => $term->name,
'slug' => $term->slug,
);
$ret[ $row['id'] ][ $term->term_id ] = $semester;
}
endif;
endforeach;
set_transient( $transient, $ret, WEEK_IN_SECONDS );
$transient_keys = get_option( 'my_transient_keys', array() );
if( !array_key_exists($transient, $transient_keys) ) {
$transient_keys[] = $transient;
update_option( 'my_transient_keys', $transient_keys );
}
endif;
}
//echo "<pre>"; print_r($ret); echo '</pre>';
return $ret;
}//end of
/* clone function for WordPress selected()
** It checkd either the option was selected or not
*/
public function selected_campus($id){
global $post;
$get_ids = get_post_meta(get_the_ID(), '_campus_id', true);
$ids = json_decode($get_ids, true);
if (in_array($id, $ids)){
$selected = 'selected="selected"';
}
return $selected;
}//
答案 0 :(得分:1)
因为选项是动态设置的。它只会在所选项目列表中选择最后一项。相反,你需要像这样更新它 -
$("#campus_id").val(["MCH Boys Branch","MCH Girls Branch","JPPS Shuja Abad Campus"]).trigger("change")