Last active
January 3, 2019 19:57
-
-
Save pjohanneson/7b050003d57c5e1034e439db05a69725 to your computer and use it in GitHub Desktop.
WordPress Settings API quickstart
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
<?php | |
/** | |
* Settings class file. | |
* | |
* @package generic-plugin | |
*/ | |
/** | |
* Settings class. | |
* | |
* The settings for the plugin are handled in this class. | |
* | |
* @since 1.0.0 | |
*/ | |
class generic_plugin_Settings { | |
const PREFIX = '_generic_plugin_'; | |
/** | |
* Constructor. | |
* | |
* @return void | |
* @since 1.0.0 | |
*/ | |
function __construct() { | |
add_action( 'admin_init', array( $this, 'settings_init' ) ); | |
add_action( 'admin_menu', array( $this, 'settings_menu' ) ); | |
} | |
/** | |
* Add the settings page. | |
* | |
* @return void | |
* @since 1.0.0 | |
*/ | |
function settings_menu() { | |
add_options_page( | |
'Generic Plugin Settings', | |
'Generic Plugin Settings', | |
'edit_others_posts', | |
'generic_plugin', | |
array( $this, 'settings_callback' ) | |
); | |
} | |
function settings_callback() { | |
echo ' | |
<div class="wrap"> | |
<h1>Generic Plugin Settings</h1> | |
<p>Some explanatory text here.</p> | |
<h2>Generic Plugin Setting Section 1</h2> | |
<form method="post" action="options.php"> | |
'; | |
do_settings_sections( self::PREFIX . 'settings' ); | |
settings_fields( self::PREFIX . 'settings_group' ); | |
submit_button(); | |
echo ' | |
</form> | |
</div> | |
'; | |
} | |
function settings_init() { | |
/** Setting section **/ | |
add_settings_section( | |
self::PREFIX. '_section_1_setting', | |
'', | |
array( $this, 'section_1' ), | |
self::PREFIX . 'settings' | |
); | |
/** Setting field **/ | |
add_settings_field( | |
self::PREFIX . 'setting_1_name', | |
'Setting 1', | |
array( $this, 'setting_1_callback' ), | |
self::PREFIX . 'settings', | |
self::PREFIX . '_section_1_setting' | |
); | |
// Register this field with our settings group. | |
register_setting( self::PREFIX . 'settings_group', self::PREFIX . 'settings' ); | |
} | |
function section_1() { | |
echo 'Setting 1 Explanatory Text'; | |
} | |
function setting_1_callback() { | |
// get the current option value | |
$settings = get_option( self::PREFIX . 'settings' ); | |
echo '<input type="text" name="' . self::PREFIX . 'settings[setting_1]' . '" value="' . $settings['setting_1'] .'" />'; | |
} | |
/** | |
* Helper monkeys. | |
* | |
* May include: usort() callbacks, content filters, etc. | |
*/ | |
} | |
new generic_plugin_Settings; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment