我创建了一个配置插件来管理站点设置,因此它是wp_options的。
我希望能够从列表中选择一个或多个项目(显示为复选框)。那些被选中的项目被保存在wp_options中,然后我想将参数与这些项目相关联。
那是我遇到问题的时候..。
当我更新所选项目时,相关参数(如URL)不会自行更新
以下是我的代码示例:
<?php
//wp_options of projects
public function page_config_init_list_projects(){
add_settings_section(
'projet-section',
'Choix des projets',
array( $this, 'print_projets_section_info' ),
'configuration-projet' // Page
);
add_settings_field(
'name',
'Liste des projets',
array( $this, 'project_chosen_callback' ),
'configuration-projet', // Page
'projet-section' // Section
);
add_settings_field(
'url',
'URL',
array( $this, 'url_callback' ),
'configuration-projet', // Page
'projet-section' // Section
);
register_setting(
'config-projets', // Option group
'projets' // Option name
);
}
//saving the projects chosen
public function project_chosen_callback(){
$items = array("project 1", "project 2", "project 3";
foreach ( $items as $id => $item) {
$names_projects = array();
foreach ($this->projetOptions as $projet){
array_push($names_projects, $projet['name']);
}
if ( in_array($item , $names_projects) ) {
$checked = 'checked="checked"';
} else $checked = null;
echo '<input type="checkbox" id="name" name="projets[][name]" value="'. $item .'"'. $checked.'/> '. $item .'</p>';
}
}
// parameter URL linked to a project chosen... here are the problems//
public function url_callback(){
foreach ($this->projetOptions as $id=>$projet){
echo $projet['name'] . ' : ';
printf(
'<input type="text" id="url" name="projets['.$id.'][url]" value="%s" /><br>',
isset( $projet['url'] ) ? esc_attr( $projet['url']) : ''
);
}
}目前,我正在尝试让projects选项响应这种类型的结构:
array(2) {
[0]=> array(2) {
["name"]=> string(8) "project 1"
["url"]=> string(4) "test"
}
[1]=> array(1) {
["name"]=> string(8) "project 2"
}
}当我选择一个项目并将其与URL相关联时,它工作得很好。但是,当我取消选择该项目时,它会将自己从wp_options中删除,但url仍然保留。此外,URL与ID相关联,而不是与项目相关联,因此当所选项目的列表发生更改时,URL会发生变化...
我真的不知道该怎么做。
发布于 2019-06-05 16:12:30
好的,如果有人遇到同样的麻烦,我找到了一个解决方案。我承认不是很好,但如果项目列表不变,那也没关系。如果有人有更好的想法,请毫不犹豫地与大家分享!
我将选择的项目与其在wp_options表中的索引相关联,因此我可以检索与该索引相关联的url。
public function project_chosen_callback(){
$items = array("project 1", "project 2", "project 3");
foreach ( $items as $id => $item) {
if ( in_array($item , $this->projetOptions['name']) ) {
$checked = 'checked="checked"';
} else $checked = null;
echo '<input type="checkbox" id="name" name="projets[name]['.$id.']" value="'. $item .'"'. $checked.'/> '. $item .'</p>';
}
}
public function url_callback(){
foreach ( $this->projetOptions['name'] as $id => $name) {
echo $name.' :<br>';
printf(
'<input type="text" id="url" name="projets[url]['.$id.']" value="%s" /><br><br>',
isset( $this->projetOptions['url'][$id] ) ? esc_attr( $this->projetOptions['url'][$id]) : ''
);
}
}https://stackoverflow.com/questions/56440153
复制相似问题