[wp-trac] [WordPress Trac] #37344: Side effects on 'nav_menu_item_args' filter when appending to arguments

WordPress Trac noreply at wordpress.org
Tue Jul 12 16:25:53 UTC 2016

#37344: Side effects on 'nav_menu_item_args' filter when appending to arguments
 Reporter:  dgwyer        |      Owner:
     Type:  defect (bug)  |     Status:  new
 Priority:  normal        |  Milestone:  Awaiting Review
Component:  Menus         |    Version:  trunk
 Severity:  normal        |   Keywords:
  Focuses:                |
 The 'nav_menu_item_args' filter allows you to filter the arguments for a
 single nav menu item which works well when you are '''overwriting'''

 When you try to '''append''' an argument the original arguments object is
 updated. This means that the next menu item passes in the updated object
 to the 'nav_menu_item_args' filter which leads to unexpected side effects.

 For demonstration purposes here's how to reproduce the issue.

 function format_menu_item_args( $args, $item, $depth ) {
         $args->before .= rand(0,9);
         return $args;
 add_filter( 'nav_menu_item_args', 'format_menu_item_args', 10, 3);

 What you should see before every menu item is a random integer between
 0-9. What happens instead is the integer from the previous menu item is
 passed into the next. So by the time the 'nth' menu item is processed you
 get 'n' integers outputted whereas only one integer per menu item should
 be outputted.

 I have added a patch to solve this by casting the $args object to an array
 early in start_el(). If left as an array this would break code already
 using the 'nav_menu_item_args' filter as an '''$args object''' is passed
 into the filter. Also code further down start_el() would need updating to
 use array rather than object notation. So, to get around this I've casted
 $args to an object again.

 This is a new object and so there won't be any issues with referencing the
 original nav menu args object. Plus, existing code using the
 'nav_menu_item_args' filter will still work fine.

 See attached screenshots for views of a nav menus before and after the
 patch is applied.

 ''Note: The default type for $args in start_el() is already specified as
 an empty array but it's actually an object that's being passed in.''

Ticket URL: <https://core.trac.wordpress.org/ticket/37344>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform

More information about the wp-trac mailing list