Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Settings API based on User ID
<?php
/*
Plugin Name: Settings API based on User ID
*/
class MySettingsPage2
{
/**
* Holds the values to be used in the fields callbacks
*/
private $options;
private $prefix;
/**
* Start up
*/
public function __construct()
{
add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
add_action( 'admin_init', array( $this, 'page_init' ) );
}
/**
* Add options page
*/
public function add_plugin_page()
{
add_options_page(
'Settings Admin', 'My Settings', 'manage_options', 'my-setting-admin', array(
$this, 'create_admin_page' )
);
}
/**
* Options page callback
*/
public function create_admin_page()
{
$this->options = get_option( $this->prefix . 'option_name' );
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2>My Settings</h2>
<form method="post" action="options.php">
<?php
settings_fields( 'my_option_group' );
do_settings_sections( 'my-setting-admin' );
submit_button();
?>
</form>
</div>
<?php
}
/**
* Register and add settings
*/
public function page_init()
{
$this->prefix = 'uid_' . get_current_user_id() . '_';
register_setting(
'my_option_group', // Option group
$this->prefix . 'option_name', // Option name
array( $this, 'sanitize' ) // Sanitize
);
add_settings_section(
'setting_section_id', // ID
'My Custom Settings', // Title
array( $this, 'print_section_info' ), // Callback
'my-setting-admin' // Page
);
add_settings_field(
'id_number', // ID
'ID Number', // Title
array( $this, 'id_number_callback' ), // Callback
'my-setting-admin', // Page
'setting_section_id' // Section
);
add_settings_field(
'id_check', 'Title', array( $this, 'id_check_callback' ), 'my-setting-admin', 'setting_section_id'
);
}
/**
* Sanitize each setting field as needed
*
* @param array $input Contains all settings fields as array keys
*/
public function sanitize( $input )
{
if( !is_numeric( $input['id_number'] ) )
$new_input['id_number'] = '';
else
$new_input['id_number'] = esc_sql( $input['id_number'] );
if( !empty( $input['id_check'] ) )
$new_input['id_check'] = esc_sql( $input['id_check'] );
return $new_input;
}
/**
* Print the Section text
*/
public function print_section_info()
{
print 'Enter your settings below:';
}
/**
* Get the settings option array and print one of its values
*/
public function id_number_callback()
{
printf(
'<input type="text" id="id_number" name="%s" value="%s" />',
$this->prefix . 'option_name[id_number]',
$this->options['id_number']
);
}
/**
* Get the settings option array and print one of its values
*/
public function id_check_callback()
{
printf(
'<input id="%1$s" name="%2$s[%1$s]" type="checkbox" %3$s />',
'id_check',
$this->prefix . 'option_name',
checked( isset( $this->options['id_check'] ), true, false )
);
}
}
if( is_admin() )
$my_settings_page2 = new MySettingsPage2();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment