Reputation: 311
I'm trying to do achieve a class-based approach to a plugin I'm currently developing but can't get my head around how to put the "mbf_page()" from within the class itself. Now I have put it put it outside the class just to make it work, but i want it to be a public function of the class. How would you do it?
<?php
class Mediabank_Frontend {
function __construct() {
add_action('init', array($this, 'mbf_add_menu'));
}
private function init() {
$this->mbf_add_menu();
}
public function mbf_add_menu() {
add_submenu_page('options-general.php', 'Mediabank settings', 'Mediabank',
'manage_options', 'mediabank-settings', 'mbf_page');
}
}
function mbf_page() {
echo '<div class="wrap"><h1>Settings</h1></div>';
}
Upvotes: 1
Views: 765
Reputation: 13870
You can use the same way you're calling your mbf_admin_menu
function. First move the mbf_page()
function into the class as a public function
, and then add it to the add_submenu_page()
callback argument as a callable function in the "array syntax": array($this, 'mbf_page')
.
class Mediabank_Frontend {
function __construct() {
add_action('init', array($this, 'mbf_add_menu'));
}
private function init() {
$this->mbf_add_menu();
}
public function mbf_add_menu() {
add_submenu_page('options-general.php', 'Mediabank settings', 'Mediabank', 'manage_options', 'mediabank-settings', array($this, 'mbf_add_menu') );
}
public function mbf_page() {
echo '<div class="wrap"><h1>Settings</h1></div>';
}
}
What array($this, 'function_name')
tells WordPress (well, PHP) is to add the function_name
from the current class instead of calling it from the globally available function scope.
You can pass callback functions in that array syntax, standard "function name" syntax, or even as a Closure/Anonymous Function:
add_submenu_page( 'parent', 'Title', 'Menu', 'cap', 'slug', 'function_name' ); // Get the globally available `function_name()` function.
add_submenu_page( 'parent', 'Title', 'Menu', 'cap', 'slug', array($this, 'function_name') ); // Get $CurrentClass->function_name() method
add_submenu_page( 'parent', 'Title', 'Menu', 'cap', 'slug', function(){ /* Do stuff */ return false; } ); // callback a defined-inline anonymous function
Upvotes: 1