I have a plugin and a part in it allows user to select the page plugin works on by specifying the id of the page. But I want that he should be able to select the page from the pages available in the website.
This can be implemented by a drop down or check boxes.
my code looks like this in the main file of plugin :
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
}
Now this works with the text area and all I want it to be a dropdown. how can I do that ?
I tried doing this :
<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>
this display the select field but not sure how to update the database option array field with what is selected in this page.
1 Answer
Change your code to this
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
}