TypeRocket v1 Pro users can now upgrade to TypeRocket v5 at their convenience.
Add Custom Fields to Menu Items
( v1 )
Requirments
Adding menu item fields is possible in WordPress 5.4+ with the addition of the wp_nav_menu_item_custom_fields
action hook. Prior to WordPress 5.4, adding custom fields to menu items was not possible without creating major conflicts between plugins.
Getting Started
First things first, to enabled WordPress menus for your theme, you need to register them. If you already have menus enabled for your theme you can skip the registration process.
In your theme's functions.php
file add the following:
// functions.php
register_nav_menu('main', 'Main Menu');
To start adding fields to your menu items, use the TypeRocket hook tr_menu_fields
. This hook provides access to a preconfigured TypeRocket form object that you must use to add your custom fields.
Take a look at this example, where we will add a text field named sub_label
.
// functions.php
add_action('tr_menu_fields', function($form) {
/** @var \TypeRocket\Elements\Form $form */
echo $form->text('Sub Label');
});
That's it! You now have a menu item field.
Note: Only simple fields work in menu items right now. Also, conditional fields are not supported for menu items at the moment but they will be added in a coming version.
Displaying the menu item field
Next, to display the menu item field, you will need to use the WordPress hook wp_nav_menu_objects
. This hook is used to modify the HTML returned by the wp_nav_menu() function.
// functions.php
add_filter('wp_nav_menu_objects', function ( $items, $args ) {
foreach( $items as &$item ) {
if( $label = tr_field('sub_label', $item) ) {
$label = esc_html($label);
$item->title .= " <b>{$label}</b>";
}
}
return $items;
}, 10, 2);
Found a typo? Something is wrong in this documentation? Fork and edit it!