Tutorial on using the ACF plugin: adding fields to menu items

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
图片[2]-如何为 WordPress 菜单项添加自定义字段并修改其 HTML

Adding Fields

The Advanced Custom Fields plugin makes it easy to add custom fields to menu items, follow the steps below.

  1. self-improvementDefining FieldsIn the Administration screen, clickAdd Newbutton to create a new field group.
  2. Add fields you want to see when editing menu items
  3. 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

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_postsACF stores all custom field values in thewp_postmetaTable.

图片[4]-如何为 WordPress 菜单项添加自定义字段并修改其 HTML

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 atitleOutput 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


Contact Us
Can't read the article? Contact us for free answers! Free help for personal, small business sites!
Tel: 020-2206-9892
QQ咨询:1025174874
(iii) E-mail: info@361sale.com
Working hours: Monday to Friday, 9:30-18:30, holidays off
© Reprint statement
This article was written by Banner1
THE END
If you like it, support it.
kudos13 share (joys, benefits, privileges etc) with others
commentaries sofa-buying

Please log in to post a comment

    No comments