Creating Custom Options Pages in WordPress

Creating Custom Options Pages in WordPress
128 Views

To create a menu for theme setting in the WordPress admin, you should use the Settings API provided by WordPress. Using this API, you can register a new options page, with fields for settings. Additionally, you can add settings to an existing options page.

That being said, let’s add the following code to the main file of a plugin or a theme’s function.php file (keeping in mind that it’s always best to create a child theme instead of altering a functions.php file):

<?php

add_action( 'admin_menu', 'cxc_theme_setting_create_menu' );

function cxc_theme_setting_create_menu() {

	//create new top-level menu
	add_menu_page( 'My Theme Settings', 'Theme Settings', 'administrator', __FILE__, 'cxc_theme_setting_page' , 'dashicons-admin-generic' );

	//call register settings function
	add_action( 'admin_init', 'cxc_register_my_theme_setting' );
}

function cxc_register_my_theme_setting() {
	//register our settings
	register_setting( 'my-theme-settings-group', 'new_option_name' );
	register_setting( 'my-theme-settings-group', 'some_other_option' );
	register_setting( 'my-theme-settings-group', 'option_etc' );
}

function cxc_theme_setting_page() {
	?>
	<div class="wrap">
		<h1>Theme Setting</h1>

		<form method="post" action="options.php">
			<?php settings_fields( 'my-theme-settings-group' ); ?>
			<?php do_settings_sections( 'my-theme-settings-group' ); ?>
			<table class="form-table">
				<tr valign="top">
					<th scope="row">New Option Name</th>
					<td><input type="text" name="new_option_name" value="<?php echo esc_attr( get_option('new_option_name') ); ?>" /></td>
				</tr>

				<tr valign="top">
					<th scope="row">Some Other Option</th>
					<td><input type="text" name="some_other_option" value="<?php echo esc_attr( get_option('some_other_option') ); ?>" /></td>
				</tr>

				<tr valign="top">
					<th scope="row">Options, Etc.</th>
					<td><input type="text" name="option_etc" value="<?php echo esc_attr( get_option('option_etc') ); ?>" /></td>
				</tr>
			</table>

			<?php submit_button(); ?>

		</form>
	</div>
<?php } ?>
Was this article helpful?
YesNo

Leave a comment

Your email address will not be published.