user3140617
user3140617

Reputation: 117

Make menu and submenu into reusable function

What basically am trying to do here is create menu and submenu which can be hooked from anywhere in the script which means that I can add new menu from anywhere in the script. What I want to do now create a reusable function for it.

On menu.php

function add_admin_menu($admin_menu_page = array()){
    return $admin_menu_page;
}

function add_admin_submenu($admin_submenu_page = array()){
    return $admin_submenu_page;
}

$admin_menu_page[] = array("Dashboard", "dashboard");
$admin_menu_page[] = array("Pages", "pages");
$admin_menu_page[] = array("Setings", "setings");

$admin_submenu_page['dashboard'][] = array("Home", "home");
$admin_submenu_page['dashboard'][] = array("Update", "update");

$admin_submenu_page['pages'][] = array("Add New Page", "new");
$admin_submenu_page['pages'][] = array("All Pages", 'pages');

$admin_submenu_page['setings'][] = array("SMTP", "smtp");
$admin_submenu_page['setings'][] = array("Theme Options", "theme-options"); 

add_admin_menu($admin_menu_page);
add_admin_submenu($admin_submenu_page);

On index.php

var_dump(add_admin_menu());

and the output is

array(0) { }

What am I missing?

In a simple question how will I make this into function?

Upvotes: 0

Views: 149

Answers (2)

Adil Abbasi
Adil Abbasi

Reputation: 3291

Try like this, if you are trying to check what is passed to array.

function add_admin_menu($admin_menu_page = array()){
  var_dump($admin_menu_page);
  return $admin_menu_page;
}

But didn't got any reason for this function what it is doing returning the same array.

Try this if you want to var_dump after calling function.

$menu = add_admin_menu($admin_menu_page);
$submenu = add_admin_submenu($admin_submenu_page);
var_dump($menu);
var_dump($submenu);

Upvotes: 1

baldrs
baldrs

Reputation: 2161

Try to store your values, perhaps like that:

function add_admin_menu($admin_menu_page = array()){
  static $menu = array();

  if(empty($menu)) $menu = $admin_menu_page;

  return $menu;
}

The pitfall of that solution that there will be only one menu at the time;

That way you can store any amount of menus you want;

$menus = array();

function add_admin_menu($admin_menu_page = array()){
  global $menus;

  $index = sizeof($menus);

  $menus[$index] = $admin_menu_page;

  return $index;
}

Note that it's returning an $index, not input array(makes no sense), so you can access that menu later and even relate it with some sumbenu.

Upvotes: 1

Related Questions