WordPress plugin admin menu, submenu

WordPress plugin admin menu, submenu

This article show how to create wordpress plugin menu and submenu.

Template plugin class

First start with this template class, create the php files under wp-content/plugins/[your_plugin_directory]

<?php
/*
Plugin Name: Codeomitted Plugin
Desription: Codeomitted plugin description
Author: Codeomitted
Author URI:
Version: 1.0
License:
License URI:
*/

class Codeomitted {
  private static $instance;

  public static function getInstance() {
    if(self::$instance == NULL) {
      self::$instance = new self();
    }
    return self::$instance;
  }

  private function __construct() {
    // implements hooks here
  }

}

Codeomitted::getInstance();

 

Create Menu

add_menu_page function contains few parameters to server it’s purpose.

  1. $page_title, = display tab/page title
  2. $menu_title, = display menu on the left
  3. $capability, =  permission
    refer: https://codex.wordpress.org/Roles_and_Capabilities#manage_options
  4. $menu_slug, = url link in the display menu on the left
  5. $function, = callback function, must use this format array($this, ‘function_name’)
  6. $icon_url, = icon
  7. $position = position
// code omitted

private function __construct() {
    // implements hooks here
    add_filter('admin_menu', array($this, 'admin_menu') );
}

function admin_menu() {
  add_menu_page('Codeomitted Title', 'Codeomitted Menu', 'manage_options', 'codeomitted-slug',  array($this,'view_page'));
}

public function view_page() {
    echo "<h1>Hello World!</h1>";
}

 

 

Create Sub Menu

// code omitted

private function __construct() {
    // implements hooks here
    add_filter('admin_menu', array($this, 'admin_menu') );
    add_filter('admin_menu', array($this, 'admin_submenu') );
}

// code omitted

function admin_submenu() {
    add_submenu_page('codeomitted-slug', 'My Setting', 'My Setting', 'manage_options', 'keys_opts', array($this,'view_setting_page'));
}

function view_setting_page() {
  echo "<h1>Setting page</h1>";
}

 

Activate the plugin

screen-shot-2016-09-14-at-2-15-03-pm

Item on the left menu

screen-shot-2016-09-14-at-2-15-22-pm

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.