我有一个插件,其中有一个部分允许用户通过指定页面id来选择插件工作的页面。但我希望他能够从网站上可用的页面中选择页面。
这可以通过下拉列表或复选框来实现。
我的代码在插件的主文件中如下所示:
register_setting( \'rex_plug_options\', \'rex_plug_options\', \'rex_plug_settings_validate\' );
add_settings_field(\'rex_plugbox_text_exit_pop_selected_pages\', \'Select Pages (comma seprated page ID E.G.: 12,32,434)\', \'rex_plugbox_text_exit_pop_selected_pages\', \'rex_plug_box\', \'rex_plug_main_box\');
<?php
}
function rex_plugbox_text_exit_pop_selected_pages(){
global $rex_plug_options;
if(!isset($rex_plug_options["rex_plugbox_text_exit_pop_selected_pages"])) {
$rex_plug_options["rex_plugbox_text_exit_pop_selected_pages"] = "";
}
?>
<textarea id="rex_plugbox_text_exit_pop_selected_pages" type="text" name="rex_plug_options[rex_plugbox_text_exit_pop_selected_pages]" ><?php echo sanitize_text_field( $rex_plug_options["rex_plugbox_text_exit_pop_selected_pages"] ); ?></textarea>
<?php
}
现在,这适用于文本区域,我希望它是一个下拉列表。我该怎么做?
我试过这样做:
<select name="rex_plug_options[page_id]">
<?php
if( $pages = get_pages() ){
foreach( $pages as $page ){
echo \'<option value="\' . $page->ID . \'" \' . selected( $page->ID, $options[\'page_id\'] ) . \'>\' . $page->post_title . \'</option>\';
}
}
?>
</select>
这将显示选择字段,但不确定如何使用此页面中选择的内容更新数据库选项数组字段。
最合适的回答,由SO网友:sakibmoon 整理而成
将代码更改为
register_setting( \'rex_plug_options\', \'rex_plug_options\', \'rex_plug_settings_validate\' );
add_settings_field(\'rex_plugbox_text_exit_pop_selected_pages\', \'Select Pages\', \'rex_plugbox_text_exit_pop_selected_pages\', \'rex_plug_box\', \'rex_plug_main_box\');
//with selectbox you cannot select multiple pages. If you need that try checkbox
function rex_plugbox_text_exit_pop_selected_pages(){
global $rex_plug_options;
if(!isset($rex_plug_options["rex_plugbox_text_exit_pop_selected_pages"])) {
$rex_plug_options["rex_plugbox_text_exit_pop_selected_pages"] = "";
}
?>
<select id="rex_plugbox_text_exit_pop_selected_pages" name="rex_plug_options[rex_plugbox_text_exit_pop_selected_pages]">
<?php
if( $pages = get_pages() ){
foreach( $pages as $page ){
echo \'<option value="\' . $page->ID . \'" \' . selected( $page->ID, $rex_plug_options["rex_plugbox_text_exit_pop_selected_pages"] ) . \'>\' . $page->post_title . \'</option>\';
}
}
?>
</select>
<?php
}