The options page lets us create an additional admin page to WordPress that allows you to build custom fields such as an input box, choose choices, color picker media uploader, etc., and manage these fields.
You can modify the admin options pages within The WordPress Dashboard area. You can also make sub-admin options pages beneath. All information is stored in the table wp_options and they are accessible globally.
To make a custom settings page within WordPress You must know about WordPress actions/hooks as well as the settings API and know how to utilize these APIs.
Create Options Page in Settings Menu
Utilize to use the add_options_page()
function to create a new submenu within Settings’ Settings primary menu.
add_action( 'admin_menu', 'custom_options_page' );function custom_options_page() {add_options_page(
'Homepage Settings', // page title
'Homepage Settings', // menu title
'manage_options', // capability to access the page
'custom-page-slug', // menu slug
'my_custom_page_content', // callback function
5 // position
);}function my_custom_page_content() {echo "This is a custom options page.";}
Read Also: How to building responsive WordPress theme using Bootstrap
Create Form and Define Settings API
Now you have to make a form in the ‘my_custom_page_content‘ function that we have a callback in the previous step.
function my_custom_page_content() {
?>
<div class="wrap">
<h1>Homepage Settings</h1>
<form method="post" action="options.php">
<?php
settings_fields( 'custom_page_settings' ); // settings group name
do_settings_sections( 'custom-page-slug' ); // a page slug
submit_button();
?>
</form>
</div>
<?php
}
Create Fields and Register Settings
We will now add a few fields to the form making use of the Settings API and registering that setting.
To include the fields on the customized options pages we’ll use to use the field add_settings_field()
function.
add_settings_field(
'homepage_banner_text',
'Homepage Banner Text',
'homepage_banner_text_field_html', // function which prints the field
'custom-page-slug', // page slug
'homepage_section', // section ID
array(
'label_for' => 'homepage_banner_text',
'class' => 'banner-text',
)
);
Callback function
function homepage_banner_text_field_html() {
$banner_text = get_option( 'homepage_banner_text' );
echo '<input type="text" id="homepage_banner_text" name="homepage_banner_text" value="'.$banner_text.'" />';
}
Then register the all fields using the register_setting()
function.
register_setting(
'custom_page_settings', // settings group name
'homepage_banner_text', // field name
'sanitize_text_field' // sanitization function
);
That’s it!!!
Leave a Reply