Have you ever felt the need to add custom fields to your menu items? It seems there isn’t a straight forward way to do this but there is certainly a way.

I wrote a script that will help you accomplish this, you can find it on github.

You only need to include both of the files found in the repository into your theme or plugin and require one of them, Menu.php.
As in the example:

require_once dirname( __FILE__ ) . '/Menu.php';

Then you can just build an array of the custom fields you need and pass it in as the argument of the Menu object.

$fields = array(
        '_mycustom_field_1' => array(
            'label' => __( 'Custom field 1', 'domain' ),
            'element' => 'input',
            'sanitize_callback' => 'sanitize_text_field',
            'attrs' => array(
                'type' => 'text',
                ),
            ),
        '_mycustom_field_2' => array(
            'label' => __( 'Custom field 2', 'domain' ),
            'element' => 'select',
            'sanitize_callback' => 'sanitize_text_field',
            'options' => array(
                'option-1' => __( 'Option 1', 'domain' ),
                'option-2' => __( 'Option 2', 'domain' ),
                ),
            ),
        );
 
        // Menu Management custom fields.
        new \Lucymtc\Theme\Menu( $fields );

You will probably need to add some styling. Bellow you can find the visual result.
Hope you find this script useful!

How to add custom fields to menu items

Leave a Reply

Your email address will not be published. Required fields are marked *