WordPress.org

Make WordPress Core

Opened 21 months ago

Last modified 20 months ago

#43113 new defect (bug)

Multiple custom item classes are returned as single string when using 'nav_menu_link_attributes' filter with Customizer preview

Reported by: lrdn Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 4.9.2
Component: Customize Keywords:
Focuses: Cc:
PR Number:

Description

Normally the variable $item->classes used in a nav_menu_link_attributes filter function returns an array of all classes associated with an item, including custom classes defined in the menu settings. However, when using the Customizer to edit an item all custom classes will be returned as a single string. Only after the changes have been published and the page reloaded will it return the expected array.

I've attached a patch that fixes the problem but I am unsure what actually causes the bug.

Attachments (1)

class-wp-customize-nav-menu-item-setting.diff (579 bytes) - added by lrdn 21 months ago.

Download all attachments as: .zip

Change History (3)

#1 @westonruter
20 months ago

Do you have an example of some code causes the bug to appear?

#2 @lrdn
20 months ago

Weston, thanks for taking a look. Simply add a nav_menu_link_attributes filter function and log the classes array of the item object. I am using the default logger in my example.

<?php

function custom_link_attributes($wp_attributes, $wp_item, $wp_args)
{
        error_log(json_encode($wp_item->classes, JSON_PRETTY_PRINT));
        return $wp_attributes;
}
add_filter('nav_menu_link_attributes', 'custom_link_attributes', 10, 3);

Now edit an existing menu item using the Customizer and define at least 2 custom CSS classes. The log output will show both classes located within the same array item.

[
    "custom-class-1 custom-class-2",
    "menu-item",
    ...
]

As soon as the changes are published, or whenever the menu items are modified in the appearance settings, the item classes will be located in separate array items as expected.

[
    "custom-class-1",
    "custom-class-2",
    "menu-item",
    ...
]

My patch is the earliest point at which I could locate and correct the malformed data, but I am guessing the cause is actually located where the string is handed over by the JavaScript request.

Note: See TracTickets for help on using tickets.