WordPress create plugin or theme options

WordPress create plugin or theme options

Its very easy to create theme or plugin option in wordpress.

In this post will create a our example plugin option in wp-admin

 

1.Create Files and Folder for plugin

We will name our example plugin “Plugin Option”. So lets create a folder inside plugins of my wordpress installation and name it “plugin-option” and inside it create one file name “plugin-option.php” and create one folder and mane it “includes”. Inside includes we will create two files one is “settings_page.php” and another one is “save_settings.php”Your plugin files and folder structure would be like this:

Now in plugin-option.php we will add below lines of at the top as plugin header and add two files  (“settings_page.php” and “save_settings.php”) from “includes” folder.

<?php 

/*
Plugin Name:  Example Plugin or theme option
Description:  This plugin for create example theme or plugin option.
Version: 1.0.1
Author: Subhasish Manna
Author URI: http://subhasishmanna.com/
License: GPLv2 or later
Text Domain: example
*/


require('includes/settings_page.php');
require('includes/save_settings.php');

 

2) Create admin page to show settings

Using add_menu_page  function you can create a admin page for you plugin or theme.

But in this Example we will use add_submenu_page function to create submenu under settings page in wp-admin.
Create one function name “our_plugin_settings_page” and hook it to  admin_menu hook. Now inside “our_plugin_settings_page” function we will use  add_submenu_page  function.  add_submenu_page takes 6 parameter.

a. parent_slug (string):  Slug of parent page(Example: “options-general.php” for add page under settings).

b. page_title (string):  Page title of your settings page (Example: “Our Settings Page” ).

c. menu_title (String):  Menu title of your settings page (Example: “Our Settings Page” ).

d. capabilitystring  (String): User capability (Example: “manage_options”, for administrator only ).

e. menu_slug (String): Slug  for your settings page (Example: “our_settings_page”).

6. Callable function (string): callback  function name (Example: “our_settings_page_call_back”).

Hope you already write add_submenu_page  function. Dont forget to define callback function right away else you will get an error.

now you code would be like this :

<?php 

function our_plugin_settings_page(){
    add_submenu_page(
                    'options-general.php',
                    __('Our Settings Page', 'example'), 
                    __('Our Settings Page', 'example'),
                    'manage_options', 
                    'our_settings_page',
                    'our_settings_page_call_back'
    );
}
add_action('admin_menu', 'our_plugin_settings_page');

function our_settings_page_call_back(){
    echo '<h1> Our Settings page </h1>';
}

Note: I have used  __  function  to make it translateable

Thats how our admin page would look like:

Now we have to add HTML on our settings page

function our_settings_page_call_back(){
   ?>
   <div id="wpbody">
   	<div id="wpbody-content">
   		<div class="wrap">
      <h1><?php _e('Our example form', 'example'); ?></h1>
   			<table class="form-table">
   				<tbody>
          <form method="post" action="admin-posts">
             <input type="hidden" name="action" value="example_admin_form" />
            <?php wp_nonce_field('our_form_save_settings_fields_verify'); ?>
            <tr>
              <th>
                <label for="text_field" ><?php _e('Text Field', 'example'); ?>
                </label>
              </th>
              <td>
                <input id="text_field"  name="text_field" value="" type="text" required >
              </td>
            </tr>
            
            <tr>
              <th>
                <label for="number_field" ><?php _e('Number Field', 'example'); ?>
                </label>
              </th>
              <td>
                <input id="number_field"  name="number_field" value="" type="number" required >
              </td>
            </tr>
            <tr>
              <th>
                <label for="checkbox_field" ><?php _e('Checkbox Field', 'example'); ?>
                </label>
              </th>
              <td>
                <input id="checkbox_field"  name="checkbox_field" value="yes" type="number" required >
              </td>
            </tr>
             
             <tr>
              <td>
              <p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="Save Changes"></p>
              </td>
             </tr>
          </form>
        </tbody>
   			</table>
   		</div>
   	</div>
   </div>
   <?php
}

 

Note that I have added one hidden with name of  “action” and added nonce field by using wp_nonce_field function. And form’s action should be “admin-post.php”

Now our Admin should look like this

3. Save settings Fields

Now in “save_settings.php” we will write a function to save our setting’s fields value. we have to hook the function to  admin_post_(action).   So our hook would be “admin_post_example_admin_form” as we added input field with name of “action” and value of “example_admin_form”.
Now we can process saving function, First will will check current user has right to edit our form by using current_user_can function and verify our nonce field and other form validation. If validation is not successful we will pass you error via $_GET and redirect back to admin page.

Add following lines of code in “save_settings.php”.

<?php 

function our_admin_form_save() {
  
  /*
  *	Check current user capability for edit settings
  */
  if(!current_user_can('manage_options')){
    wp_redirect(get_admin_url().'admin.php?page=our_settings_page&save_error='.urlencode('You are not allowed to edit this seetings') );
    exit();
  }

  /*
  *	Verify nonce field
  */
  check_admin_referer('our_form_settings_fields_verify');
  
  /*
  *	Collecting values on array is user pass any value
  */ 
  $values = array();
  if( isset($_POST['text_field']) ){
  $text_field = sanitize_text_field( $_POST['text_field']);
  $values['text_field'] = $text_field;
  }
  if( isset($_POST['number_field']) ){
  $number_field = sanitize_text_field($_POST['number_field']);
  $values['number_field'] = $number_field;
  }
  if( isset($_POST['checkbox_field']) ){
  $checkbox_field = sanitize_text_field( $_POST['checkbox_field']);
  $values['checkbox_field'] = $checkbox_field;
  }
  /*
  *	Add option for our form if not exist 
  */ 
  if(!get_option( 'our_settings' )){

        add_option( 'our_settings', array());
    }
  /*
  *	update settings 
  */ 
  
  update_option( 'our_settings', $values);
  wp_redirect(get_admin_url().'admin.php?page=our_settings_page&save_success='.urlencode('Setting saved successfully') );
  exit();
  
}

add_action( 'admin_post_example_admin_form', 'our_admin_form_save' );

Note: dont forget to sanitize you fields

Now if you check your database using this query(“SELECT * FROM `wp_options` WHERE `option_name`=‘our_settings’“), yiu will see all values are saved there.

Now you have to show  saved value in form field. So update “our_settings_page_call_back” function with following with this.

function our_settings_page_call_back(){
   ?>
   <div id="wpbody">
   	<div id="wpbody-content">
   		<div class="wrap">
      <h1><?php _e('Our example form', 'example'); ?></h1>
   			<?php 
              if(isset($_GET['save_error'])){
                echo '<div style="background: #ff000061; padding: 11px 5px; border-radius: 6px; font-size: 15px;" class="sour_validation_msg">'.urldecode( $_GET['save_error'] ).'</div>';
              }
              if(isset($_GET['save_success'])){
                echo '<div style="background:#00800063; padding: 11px 5px; border-radius: 6px; font-size: 15px;" class="sour_validation_msg">'.urldecode( $_GET['save_success'] ).'</div>';
              }
              
               $our_settings = get_option( 'our_settings' );
            ?>
      <table class="form-table">
   				<tbody>
          <form method="post" action="admin-post.php">
             <input type="hidden" name="action" value="example_admin_form" />
            <?php wp_nonce_field('our_form_settings_fields_verify'); ?>
            <tr>
              <th>
                <label for="text_field" ><?php _e('Text Field', 'example'); ?>
                </label>
              </th>
              <td>
                <input id="text_field"  name="text_field" value="<?php if(isset($our_settings['text_field'])){ echo $our_settings['text_field']; } ?>" type="text" required >
              </td>
            </tr>
            
            <tr>
              <th>
                <label for="number_field" ><?php _e('Number Field', 'example'); ?>
                </label>
              </th>
              <td>
                <input id="number_field"  name="number_field" value="<?php if(isset($our_settings['number_field'])){ echo $our_settings['number_field']; } ?>" type="number" required >
              </td>
            </tr>
            <tr>
              <th>
                <label for="checkbox_field" ><?php _e('Checkbox Field', 'example'); ?>
                </label>
              </th>
              <td>
                <input id="checkbox_field"  <?php if(isset($our_settings['checkbox_field']) && $our_settings['checkbox_field'] == 'yes' ){ echo 'checked'; } ?>  name="checkbox_field" value="yes" type="checkbox" required >
              </td>
            </tr>
             
             <tr>
              <td>
              <p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="Save Changes"></p>
              </td>
             </tr>
          </form>
        </tbody>
   			</table>
   		</div>
   	</div>
   </div>
   <?php
}

No success you will see message like this

 

Congratulation now you know to  create plugin or theme options.

Get full code here    

Thanks all & happy Coding.

Facebook Comments
No Comments

Post A Comment