Create a gist now

Instantly share code, notes, and snippets.

abstract wordpress AdminMenu class
<?php # -*- coding: utf-8 -*-
namespace my_plugin\admin_menu;
use my_plugin\functions as Functions;
/**
* Abstract AdminMenu class
*
* Provides methods to create admin menues
*/
abstract class AdminMenu{
private $textdomain;
public function register_menu( $menu ){
$instance = $this;
$instance->textdomain = Functions\get_textdomain();
add_action( 'admin_menu', function() use ( $instance, $menu ){
if( ! property_exists( $menu, 'type' ) ) {
return new \WP_Error(
'menu-type-missing',
__( 'The menutype you want to register is missed', $instance->textdomain )
);
}
if( $menu->type == 'main' ){
$instance->add_menu( $menu );
}else if( $menu->type == 'sub' ){
$instance->add_submenu( $menu );
}
return true;
} );
}
/**
* Add a main menu
*
* @see add_menu_page()
* @param object $args
*/
private function add_menu( $args = false ){
$defaults['page_title'] = 'Mainmenu';
$defaults['menu_title'] = 'Mainmenu';
$defaults['capability'] = 'administrator';
$defaults['menu_slug'] = 'mainmenu';
$defaults['function'] = '';
$defaults['icon_url'] = '';
$defaults['position'] = null;
$args = wp_parse_args( $args, $defaults );
add_menu_page(
esc_html__( $args['page_title'], $this->textdomain ),
esc_html__( $args['menu_title'], $this->textdomain ),
$args['capability'],
$args['menu_slug'],
$args['function'],
$args['icon_url'],
$args['position']
);
}
/**
* * Add a submenu
*
* @see add_submenu_page()
* @param $args
*/
private function add_submenu( $args = false ){
$defaults['parent_slug'] = 'submenu';
$defaults['page_title'] = 'Submenu';
$defaults['menu_title'] = 'submenu';
$defaults['capability'] = 'administrator';
$defaults['menu_slug'] = 'submenu';
$defaults['function'] = 'submenu';
$args = wp_parse_args( $args, $defaults );
add_submenu_page(
$args['parent_slug'],
esc_html__( $args['page_title'], $this->textdomain ),
esc_html__( $args['menu_title'], $this->textdomain ),
$args['capability'],
$args['menu_slug'],
$args['function']
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment