Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mikeott/b35a8f3fc254261219e1696d6ae3558e to your computer and use it in GitHub Desktop.
Save mikeott/b35a8f3fc254261219e1696d6ae3558e to your computer and use it in GitHub Desktop.
WordPress plugin Sanitise and Validate settinhgs fields
<?php
// In the main plugin file:
/* Register settings */
function my_cool_plugin_settings_init() {
register_setting (
'my_cool_plugin_settings',
'my_cool_plugin_settings',
'my_cool_plugin_settings_validate'
);
}
add_action( 'admin_init', 'my_cool_plugin_settings_init' );
/* Sanitize and validate */
function my_cool_plugin_settings_validate( $input ) {
$output = array();
foreach ( $input as $key => $value ) {
if ( isset( $input[$key] ) ) {
if ( is_array( $input[$key] ) ) {
$output[$key] = array_map( 'sanitize_text_field', $input[$key] );
} else {
/* Preserve line breaks while stripping HTML tags */
$output[$key] = wp_kses( $input[$key], array( 'br' => array() ) );
}
}
}
return $output;
wp_verify_nonce($_POST['my-cool-plugin-settings'], 'save-my-cool-plugin-settings');
}
// The settings page form
<form method="post" action="options.php">
// All fields here....
<?php wp_nonce_field( 'save-my-cool-plugin-settings','my-cool-plugin-settings' ) ?>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment