Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom menu page with settings section and field
<?php
/**
* Class Admin.
*/
class Admin {
/**
* Admin settings array.
*
* @var array
*/
private $admin_settings;
/**
* Constructor.
*/
public function __construct() {
$this->admin_settings = get_option( 'admin-menu-settings' );
/**
* Actions.
*/
add_action( 'admin_menu', [ $this, 'add_admin_menu' ] ); // To register custom menu setting.
add_action( 'admin_init', [ $this, 'add_admin_menu_init' ] ); // To register setting sections and fields for custom menu.
}
/**
* To add Admin Menu tabs.
*
* @return void
*/
public function add_admin_menu() {
// This will create menu tab in admin sidebar and its page layout called from admin_menu_html callback function.
add_menu_page(
__( 'Admin Menu Settings', 'default' ),
__( 'Admin Menu', 'default' ),
'manage_options',
'admin-menu',
[ $this, 'admin_menu_html' ]
);
}
/**
* Admin Menu setting page html.
*
* @return void
*/
public function admin_menu_html() {
// User Require Capability to edit page.
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'default' ) );
}
?>
<div class="wrap">
<h1>
<?php echo esc_html( get_admin_page_title() ); ?>
</h1>
<form method="post" action="options.php">
<?php
settings_fields( 'admin-menu' );
do_settings_sections( 'admin-menu-page' );
submit_button();
?>
</form>
</div>
<?php
}
/**
* Undocumented function
*
* @return void
*/
public function add_admin_menu_init() {
register_setting(
'admin-menu',
'admin-menu-settings'
);
add_settings_section(
'admin-menu-general-settings',
__( 'Global Settings', 'default' ),
'__return_empty_string',
'admin-menu-page'
);
add_settings_field(
'text-field',
__( 'Text Field', 'default' ),
[ $this, 'get_text_field' ],
'admin-menu-page',
'admin-menu-general-settings'
);
add_settings_field(
'checkbox-field',
__( 'Checkbox Field', 'default' ),
[ $this, 'get_checkbox_field' ],
'admin-menu-page',
'admin-menu-general-settings' // Section name.
);
}
/**
* Prints checkbox field.
*
* @return void
*/
public function get_checkbox_field() {
echo sprintf( '<input name="admin-menu-settings[checkbox-field]" type="checkbox" id="checkbox-field" value="1" %s>', checked( $this->admin_settings['checkbox-field'], '1', false ) );
}
/**
* Prints text field.
*
* @return void
*/
public function get_text_field() {
echo sprintf( '<input name="admin-menu-settings[text-field]" type="text" id="text-field" value="%s" class="regular-text">', esc_attr( $this->admin_settings['text-field'] ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.