Add Custom Data Attributes to WordPress Menu Items

In this tutorial, we will learn how to add custom data attributes to menu items in WordPress. Custom data attributes allow you to attach additional information to menu items, which can be useful for various purposes like tracking, styling, or functionality enhancements. We will achieve this without modifying the parent theme files by utilizing a child theme and following WordPress coding standards. No plugins will be used in this tutorial to maintain code simplicity and flexibility.

Before proceeding with any customizations in WordPress, it’s essential to set up a child theme. A child theme acts as a safe and efficient way to make modifications without affecting the parent theme. If you haven’t set up a child theme yet, follow this tutorial on How to Create a Child Theme for Customization. It will guide you through the process and ensure that your customizations remain intact even after theme updates.

Add Custom Fields to Menu Item Editor

Assuming you already have a child theme set up, open the functions.php file of your child theme in a code editor. Inside the functions.php file, add the following code:

// Add custom fields to menu item.
function add_custom_fields_to_menu_item( $item_id, $item, $depth, $args ) {
	$data_attribute_value = get_post_meta( $item_id, '_menu_item_data_attribute', true );
	?>
	<div class="field-custom-description description-wide">
		<label for="edit-menu-item-data-attribute-<?php echo esc_attr( $item_id ); ?>">
			<?php esc_html_e( 'Data Attribute', 'your-theme-text-domain' ); ?>
			<br />
			<input type="text" id="edit-menu-item-data-attribute-<?php echo esc_attr( $item_id ); ?>"
				class="widefat edit-menu-item-data-attribute"
				name="menu-item-data-attribute[<?php echo esc_attr( $item_id ); ?>]"
				value="<?php echo esc_attr( $data_attribute_value ); ?>" />
			<p class="description"><?php esc_html_e( 'Enter custom data attribute(s) in the format "data-attribute1=value1&data-attribute2=value2". Separate multiple attributes with an ampersand (&).', 'your-theme-text-domain' ); ?></p>
		</label>
	</div>
	<?php
}
add_action( 'wp_nav_menu_item_custom_fields', 'add_custom_fields_to_menu_item', 10, 4 );
Code language: PHP (php)

This code adds a custom field to the menu item editor in the WordPress backend. The field allows users to enter custom data attributes in the specified format. A description is provided to guide users on the correct input format.

Save Custom Fields

To save the custom fields entered by the user, add the following code below the previous code:

// Save custom fields.
function save_custom_fields( $menu_id, $menu_item_db_id, $menu_item_args ) {
	if ( isset( $_POST['menu-item-data-attribute'][ $menu_item_db_id ] ) ) {
		$data_attribute_value = sanitize_text_field( $_POST['menu-item-data-attribute'][ $menu_item_db_id ] );
		update_post_meta( $menu_item_db_id, '_menu_item_data_attribute', $data_attribute_value );
	}
}
add_action( 'wp_update_nav_menu_item', 'save_custom_fields', 10, 3 );
Code language: PHP (php)

This code handles the saving of the custom field data when a menu item is updated. It retrieves the entered value, sanitizes it, and saves it as the custom field “_menu_item_data_attribute” using the update_post_meta() function.

Display Custom Data Attributes on Frontend

To display the custom data attributes on the frontend menu, add the following code below the previous code:

// Add attribute frontend.
function add_custom_data_attribute_to_menu_items( $atts, $item, $args, $depth ) {
	$custom_data_attribute = get_post_meta( $item->ID, '_menu_item_data_attribute', true );
	if ( ! empty( $custom_data_attribute ) ) {
		parse_str( $custom_data_attribute, $custom_atts );
		$atts = array_merge( $atts, $custom_atts );
	}
	return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_custom_data_attribute_to_menu_items', 10, 4 );
Code language: PHP (php)

This code retrieves the saved custom data attributes for each menu item and adds them to the attributes of the menu link on the frontend. The parse_str() function is used to parse the custom data attribute string and convert it into an array of attribute-value pairs. The attributes are then merged with the existing attributes using array_merge().

Save and Test

Save the modified functions.php file and upload it to your child theme directory. Now, navigate to the WordPress backend and edit a menu item. You should see the custom data attribute field. Enter your desired custom data attribute(s) in the specified format and save the menu item.

View Custom Data Attributes on Frontend

Visit your website’s frontend and inspect the menu items. You should see the custom data attributes added as part of the menu link attributes.

That’s it! You have successfully learned how to add custom data attributes to menu items in WordPress using a child theme. By following the provided steps and adhering to WordPress coding standards, you can easily enhance your menu items with additional information. Custom data attributes provide flexibility for various purposes such as tracking, styling, or implementing custom functionality.

Remember to always use a child theme to preserve your modifications and ensure better compatibility and maintainability. By avoiding the use of plugins and relying on code snippets, you have more control over your customizations.

Feel free to experiment and customize the code further to suit your specific needs. Happy coding!

Leave your feedback and help us improve šŸ¶

We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee ā˜•ļø or donating via PayPal šŸ’°.

More free knowledge, because why not?

Your thoughts matter, leave a reply šŸ’¬

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