[resolved] Custom Menu Classes (6 posts)

  1. Star Verte LLC
    Posted 3 years ago #

    When creating a custom menu, you can give a menu item a CSS class via the "CSS Classes (optional)" field. However, this adds a class to the <li> element, and I want to add a class to the <a> element. How do I do this?

  2. vtxyzzy
    Posted 3 years ago #

    I am curious why you can't use a selector like

    li.myclass a {

    to do what you want.

  3. Star Verte LLC
    Posted 3 years ago #

    I am using it for creating a Modal Dialog window. I need to define for a particular link on a menu to open in a modal window instead of a new page.

  4. keesiemeijer
    Posted 3 years ago #

    Create a custom walker for wp_nav_menu and put it in your theme's functions.php: custom walker

    Here in the walker I add a class to a nav_menu link to a Page with ID 108:

    // add a class to the link
    if($item->object == 'page' && $item->object_id == 108){
      $attributes .= ' class="my-custom-class-on-link"';

    For post links use $item->object == 'post' and the ID of the post.

    categories: $item->object == 'category'
    for tags: $item->object == 'post_tag'
    custom post type: $item->object == 'book' (name you registered your post type under)

    call wp_nav_menu() like this in your template files:

    <?php wp_nav_menu( array( 'theme_location' => 'primary', 'walker' => new My_Nav_Menu_Walker() ) ); ?>
  5. Star Verte LLC
    Posted 3 years ago #

    That works too. I ended up doing

    function add_menuclass($ulclass) {
    return preg_replace('/<a rel="modal"/', '<a rel="modal" class="lbpModal"', $ulclass, 1);

    and then specified the XFN Link Relationship for those links as "modal"

    I understand your code, however am unfamiliar with the term "walker." What does that refer to?

  6. keesiemeijer
    Posted 3 years ago #

    A walker makes use of the Walker class to output the HTML for functions as wp_list_pages(), wp_list_categories(), wp_nav_menu().

    Glad you got it resolved.

Topic Closed

This topic has been closed to new replies.

About this Topic