Last active
October 25, 2020 10:23
-
-
Save ibrokemywp/61a3dec8dee4253cc58c to your computer and use it in GitHub Desktop.
Store all of your options in a single serialized array in the database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Register a single setting to store all of your options in the database | |
*/ | |
register_setting( 'myslug_option_group', 'myslug', 'myslug_sanitize_options_array' ); | |
/** | |
* Define each of your settings | |
*/ | |
add_settings_field( | |
'name', | |
__( 'Name', 'textdomain' ), | |
'myslug_print_text_field', | |
'page_slug', | |
'section_slug', | |
array( 'slug' => 'name' ) | |
); | |
add_settings_field( | |
'birthday', | |
__( 'Birthday', 'textdomain' ), | |
'myslug_print_text_field', | |
'page_slug', | |
'section_slug', | |
array( 'slug' => 'birthday' ) | |
); | |
add_settings_field( | |
'job', | |
__( 'Job', 'textdomain' ), | |
'myslug_print_text_field', | |
'page_slug', | |
'section_slug', | |
array( 'slug' => 'job' ) | |
); | |
/** | |
* Print each of your settings using brackets to nest this value | |
* under your setting, eg - myslug[myoption] | |
*/ | |
function mysql_print_text_field( $args ) { | |
?> | |
<input type="text" name="myslug[<?php echo esc_attr( $args['slug'] ); ?>]"> | |
<?php | |
} | |
/** | |
* When sanitizing the values, you need to loop over each value and | |
* ensure it's sanitized. Be strict here, so no one can pass extra | |
* settings fields | |
*/ | |
function myslug_sanitize_options_array( $value ) { | |
$new_value = array(); | |
foreach( $value as $id => $option ) { | |
// Sanitize each setting and add it to $new_value | |
} | |
return $new_value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment