Let us now look at how a developer can add a new Theme Option using the WordPress Settings API. We list the tasks and the corresponding APIs for adding a new checkbox Theme Option to a theme. As a reference for creating a complete working example, we have also added the sample code for adding a new Menu item and page. You may change it as per requirement.
Step 1: Create a new Menu for WordPress Theme Options
Output Settings Page
Step 2: Add Blank Page for new Menu
Output settings page
Step 3: Add and display custom sections to new Page
Step 4: Add Settings Field to Section
Output settings page
Step 5: Retrieve the Settings Field value
Let us now see how to retrieve and use the value of the settings field option. We modify the settings field display callback to set the initial value of a checkbox field. We use the get_option API to retrieve the value of the option from the database.
$value = get_option('first_field_option');,
In the sample code below, the value of the checkbox is set according to the value saved in the database. If the user checks the checkbox and submits the changes, then next time when he opens the “Theme Customization” tab, the checkbox will be checked as per value saved in the database.
function theme_option_page() {
?>
<div class="wrap">
<h1>Custom Theme Options Page</h1>
<form method="post" action="options.php">
<?php
// display settings field on theme-option page
settings_fields("theme-options-grp");
// display all sections for theme-options page
do_settings_sections("theme-options");
submit_button();
?>
</form>
</div>
<?php}
function add_theme_menu_item() {
add_theme_page("Theme Customization", "Theme Customization", "manage_options", "theme-options", "theme_option_page", null, 99);}
add_action("admin_menu", "add_theme_menu_item");
function theme_section_description(){
echo '<p>Theme Option Section</p>';}
function options_callback(){
$options = get_option( 'first_field_option' );
echo '<input name="first_field_option" id="first_field_option" type="checkbox" value="1" class="code" ' . checked( 1, $options, false ) . ' /> Check for enabling custom help text.';
}
function test_theme_settings(){
add_option('first_field_option',1);// add theme option to database
add_settings_section( 'first_section', 'New Theme Options Section',
'theme_section_description','theme-options');
add_settings_field('first_field_option','Test Settings Field','options_callback',
'theme-options','first_section');//add settings field to the “first_section”
register_setting( 'theme-options-grp', 'first_field_option');
}
add_action('admin_init','test_theme_settings');
No comments:
Post a Comment