Skip to content

Admin Pages

Miguel Muscat edited this page Nov 30, 2022 · 2 revisions

Admin pages refer to the content that is rendered to a logged-in user in the WordPress admin content area. Pages are typically associated with Admin Menus.

Creating a page

You can create an admin page by simply invoking the constructor:

use RebelCode\WpSdk\Wp\AdminPage;

$page = new AdminPage(
    // The page title
    'My Page',
    // The render function
    function () {
        return 'Hello world!';
    }
);

Note that render functions for admin pages should return their content, not echo it.

Rendering a page

Pages can be rendered in a number of ways, depending on your use case:

Render the page's content to a string, then echo it:

echo $page->render();

Obtain an echo function to use as a callback:

$echo = $page->getEchoFn();
$echo();

Use with admin menus and submenus:

use RebelCode\WpSdk\Wp\AdminMenu;
use RebelCode\WpSdk\Wp\AdminSubMenu;

new AdminMenu($page, /* ... */);
AdminSubMenu::forPage($page, /* ... */);

Refer to the documentation for Admin Menus for more information.

Services

Factories for menus and submenus can be created easily using their corresponding static factory methods.

use RebelCode\WpSdk\Wp\AdminMenu;
use RebelCode\WpSdk\Wp\AdminPage;
use RebelCode\WpSdk\Wp\AdminSubMenu;
use RebelCode\WpSdk\Module;
use Dhii\Services\Factories\FuncService;

class MyModule extends Module
{
    public function getFactories(): array
    {
        return [
            'my_page' => AdminPage::factory('My Page', 'my_page/render_fn'),
            'my_page/render_fn' => new FuncService([], function () {
                return 'Hello world!';
            }),
        ];
    }
}

Note: The factory method takes the similar arguments as the constructor, except for the render function, which should be the key of the render function service.

Clone this wiki locally