Skip to content

Instantly share code, notes, and snippets.

@jhaus
Created December 21, 2010 06:35
Show Gist options
  • Save jhaus/749579 to your computer and use it in GitHub Desktop.
Save jhaus/749579 to your computer and use it in GitHub Desktop.
Wordpress Settings API Example Usage
<?php
/*
Plugin Name: Settings API Example
Plugin URI: http://wpengineer.com/
Description: Complete and practical example of use of the Settings API to add fields on the Writing option page
Author: Ozh
Author URI: http://ozh.org/
*/
// We'll use ozhwpe (Ozh / WP Engineer) as a prefix throughout the plugin
// Register and define the settings
add_action('admin_init', 'ozhwpe_admin_init');
function ozhwpe_admin_init(){
register_setting(
'writing', // settings page
'ozhwpe_options', // option name
'ozhwpe_validate_options' // validation callback
);
add_settings_field(
'ozhwpe_notify_boss', // id
'Boss Email', // setting title
'ozhwpe_setting_input', // display callback
'writing', // settings page
'default' // settings section
);
}
// Display and fill the form field
function ozhwpe_setting_input() {
// get option 'boss_email' value from the database
$options = get_option( 'ozhwpe_options' );
$value = $options['boss_email'];
// echo the field
?>
<input id='boss_email' name='ozhwpe_options[boss_email]'
type='text' value='<?php echo esc_attr( $value ); ?>' /> Boss wants to get a mail when a post is published
<?php
}
// Validate user input
function ozhwpe_validate_options( $input ) {
$valid = array();
$valid['boss_email'] = sanitize_email( $input['boss_email'] );
// Something dirty entered? Warn user.
if( $valid['boss_email'] != $input['boss_email'] ) {
add_settings_error(
'ozhwpe_boss_email', // setting title
'ozhwpe_texterror', // error ID
'Invalid email, please fix', // error message
'error' // type of message
);
}
return $valid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment