WordPress Menus are powerful tools for organizing a set of links (menu items), and themes often use these menus to create navigation features. This guide will demonstrate in detail how to add custom fields to WordPress menu items and modify the HTML output of menu items. The plugins used areACF(Advanced Custom Fields)The
ACFThe plugin is now renamed SCF and is installed in the Plugin Marketplace:
![图片[1]-如何为 WordPress 菜单项添加自定义字段并修改其 HTML](https://www.361sale.com/wp-content/uploads/2024/11/20241121113500520-image.png)
![图片[2]-如何为 WordPress 菜单项添加自定义字段并修改其 HTML](https://www.361sale.com/wp-content/uploads/2024/11/20241121104643193-image.png)
Adding Fields
The Advanced Custom Fields plugin makes it easy to add custom fields to menu items, follow the steps below.
- self-improvementDefining FieldsIn the Administration screen, clickAdd Newbutton to create a new field group.
- Add fields you want to see when editing menu items
- in positionlower case, selectmenu itemRule and select "All" (to display this field group on all menu items) or Specific Menu/Location (to display this field group only for specific menu items)
![图片[3]-如何为 WordPress 菜单项添加自定义字段并修改其 HTML](https://www.361sale.com/wp-content/uploads/2024/11/20241121104042558-image.png)
edit a field
Once a field group has been created and designated to appear on the menu item edit screen, it can be edited by navigating to theAppearance > Menuadministration page to edit the field values.
WP stores each menu item as a post object in thewp_posts
ACF stores all custom field values in thewp_postmeta
Table.
![图片[4]-如何为 WordPress 菜单项添加自定义字段并修改其 HTML](https://www.361sale.com/wp-content/uploads/2024/11/20241121104151658-image.png)
Display Fields
The HTML for WordPress menu items can be easily customized with the wp_nav_menu_objects filter. This filter is run every time the menu is rendered (via the wp_nav_menu() function) and allows you to modify the menu item objects. Each object contains atitle
Output values in each menu link element<a>
The
This example shows how to modify all the menu item objects with the new "icon (computing)"Attach an icon when a value exists for the field.
add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);
function my_wp_nav_menu_objects( $items, $args ) {
// loop
foreach( $items as &$item ) {
// vars
$icon = get_field('icon', $item);
// append icon
if( $icon ) {
$item->title . = ' ';
}
}
// return
return $items;
}
reach a verdict
Here's how it appears in the browser. Notice the new iconsElements!
![图片[5]-如何为 WordPress 菜单项添加自定义字段并修改其 HTML](https://www.361sale.com/wp-content/uploads/2024/11/20241121104320582-image.png)
Link to this article:https://www.361sale.com/en/27348The article is copyrighted and must be reproduced with attribution.
No comments