1

I have a menu listing all of my products categories in Woocommerce. I need to add an attribute data-relation to each <li> tag and the value for each one would be the ID of the category.

I success to do it for the <a> tag. Does it exist a filter for <li>?

Here is the PHP filter function:

function category_menu_id_attribute ($atts, $item, $args) {
  $atts['data-relation'] = $item->object_id;
  return $atts;
  }
add_filter('nav_menu_link_attributes', 'category_menu_id_attribute', 10, 3);

Thank you for the help.

6
  • Note that the above code will attach the ID of the nav_item post, not the term/product category. Nav menus are a taxonomy, and each item in the menu is a post of type nav_item. Why do you need this?
    – Tom J Nowell
    Commented Feb 1, 2021 at 18:27
  • Unfortunately, no, there's no such filter yet. You'd need to use a custom walker and override the Walker_Nav_Menu::start_el() which builds the <li> tag.
    – Sally CJ
    Commented Feb 2, 2021 at 6:13
  • And actually @TomJNowell, object_id is the ID of the "object" (post, category, tag, etc.) originally represented by the nav menu item, and the nav menu item ID is stored in $item->ID and $item->db_id. See wp_setup_nav_menu_item().
    – Sally CJ
    Commented Feb 2, 2021 at 6:19
  • Thanks for your answer @TomJNowell, I need it to create a relation between a menu with categories and a list of these categories with thumbnails. Commented Feb 2, 2021 at 9:36
  • Thank you @SallyCJ, I also read about the custom walker. But the tutorials I saw are 10-8 years old so I hoped there was a new filter. Anyway it's fine, I will use the code provided above and create the attribute on the <a> tag. Thanks again! Commented Feb 2, 2021 at 9:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.