Menus

In HivePress, menus are implemented as PHP classes with specific properties, such as the menu items and HTML attributes. For example, the User_Account menu contains the user account menu items, and it's displayed on the account subpages.

Creating menus

If you are developing a custom HivePress extension, you may need to create a new menu. To do this, create a new class-{menu-name}.php file (use lowercase letters, numbers, and hyphens only) in the includes/menus extension subdirectory and HivePress will load it automatically.

Then, define the menu PHP class. The class name should be based on the file name but with underscores instead of hyphens and no lowercase restriction (e.g. Foo_Bar class for the class-foo-bar.php file). Pick a name that is unique enough to avoid conflicts with other HivePress menus.

The following menu parameters are available:

  • attributes - an array of HTML attributes;

  • items - the menu item parameters.

Each menu item is defined with these parameters:

  • label - menu item label;

  • route - route name for linking;

  • url - custom URL if no route is set.

The code example below implements a menu with two items. The first item is based on the listings_view_page URL route, so it's linked to the Listings page. The second item is linked to a custom URL set in the url parameter.

<?php
namespace HivePress\Menus;

use HivePress\Helpers as hp;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

class Foo_Bar extends Menu {
	public function __construct( $args = [] ) {
		$args = hp\merge_arrays(
			[
				// Define the menu items.
				'items' => [
					'first_item'  => [
						'label'  => 'First Item',
						'route'  => 'listings_view_page',
						'_order' => 123,
					],

					'second_item' => [
						'label'  => 'Second Item',
						'url'    => 'https://example.com',
						'_order' => 321,
					],
				],
			],
			$args
		);

		parent::__construct( $args );
	}
}

In the same way, you can create custom menus for your HivePress extension.

Customizing menus

You can customize any of the existing menus using hooks. For example, the code below adds a new item with the "Custom item" label to the user account menu.

add_filter(
	'hivepress/v1/menus/user_account',
	function( $menu ) {
		$menu['items']['custom_item'] = [
			'label'  => 'Custom item',
			'url'    => 'https://example.com',
			'_order' => 123,
		];

		return $menu;
	}
);

Similarly, you can customize any menu in HivePress or its extensions.

Last updated