Skip to content

Instantly share code, notes, and snippets.

@kostasdizas
Created November 28, 2010 04:27
Show Gist options
  • Save kostasdizas/718588 to your computer and use it in GitHub Desktop.
Save kostasdizas/718588 to your computer and use it in GitHub Desktop.
create a simple wordpress (2.7+) settings page that includes user options. ( option_two can be different for each user ). The uninstall.php file helps remove all the plugin options.
<?php
// ...
// create custom plugin settings menu
add_action('admin_menu', 'my_plugin_create_menu');
function my_plugin_create_menu() {
//create new top-level menu
add_menu_page('My Plugin Settings', 'My Plugin Settings', 'administrator', __FILE__, 'my_plugin_settings_page', plugins_url('/images/icon.png', __FILE__));
//call register settings function
add_action( 'admin_init', 'register_mysettings' );
}
function register_mysettings() {
//register our settings
register_setting( 'my-plugin-settings-group', 'option_one' );
register_setting( 'my-plugin-settings-group', 'option_two', 'option_two_cb' );
}
function option_two_cb( $input ) {
// store the input for the current user and then grab the same variable
// with get option and replace the input.
$user = wp_get_current_user();
update_user_option($user->id, 'option_two', $input);
$input = get_option('option_two');
return $input;
}
function my_plugin_settings_page() {
?>
<div class="wrap">
<h2>My Plugin</h2>
<form method="post" action="options.php">
<?php settings_options( 'my-plugin-settings-group' ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row">Option One:</th>
<td><input type="text" name="option_one" value="<?php echo get_option('option_one'); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Option Two:</th>
<td><input type="text" name="option_two" value="<?php echo get_user_option('option_two'); ?>" /></td>
</tr>
</table>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
</p>
</form>
</div>
<?php
}
// ...
?>
<?php
// ...
//delete all options
function my_plugin_uninstall_options() {
global $wpdb;
$users = $wpdb->get_col( 'SELECT `'. $wpdb->users.ID .'` FROM `'. $wpdb->users .'`' );
foreach ( $users as $user_id )
delete_user_option( $user_id, 'option_two' );
delete_option( 'option_one' );
delete_option( 'option_two' ); // it is used as a fallback
}
my_plugin_uninstall_options();
// ...
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment