Add Custom Classes to Wordpress Navigation Anchor

2019-08-19 00:25发布

问题:

How is it possible for me to create a field that adds a custom class to the wordpress navigation items anchor tags and not list items

So I want this:

    <li><a class="custom classes" href="example"></a></li>
    <li><a class="different custom classes" href="example"></a></li>
    <li><a class="other custom classes" href="example"></a></li>

Can someone please help me?

---- Edit :) Sorry lol

Your walker works perfectly on a fresh wp menu. But I tried to add that to the actual theme later on and there is a slight problem :P

class Maha_Mega_Menu extends Walker_Nav_Menu {

function start_lvl(&$output, $depth = 0, $args = array()) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<div class=\"nav-sub-menus\"><ul>\n";
}

function end_lvl(&$output, $depth = 0, $args = array()) {
    $indent = str_repeat("\t", $depth);
    $output .= "$indent</ul></div>\n";
}

function start_el( &$output, $item, $depth = 0, $args = array(), $current_object_id = 0 ) {

    global $wp_query;
    $cat = $item->object_id;
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    $class_names = $value = '';
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;
    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
    $class_names = ' class="' . esc_attr( $class_names ) . '"';
    $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';

    $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
    $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
    $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

    $item_output = $args->before;
    $item_output .= '<a'. $attributes .'>';
    $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
    $item_output .= '</a>';
    $children = get_posts(array(
        'post_type' => 'nav_menu_item',
        'nopaging' => true,
        'numberposts' => 1,
        'meta_key' => '_menu_item_menu_item_parent',
        'meta_value' => $item->ID
    ));
    // echo $depth.' x ';
    if ( ! empty( $children ) || ! get_field( 'menu_latest_posts', 'category_' . $cat ) || get_field( 'menu_latest_posts', 'category_' . $cat ) == 'latest_posts_on' ) {
        // if ( $depth == 0 && $item->object == 'category' || $item->object == 'page' ) {
        if ( $depth == 0 && $item->object == 'category' || $item->object == 'page' || $item->object == 'custom' ) {
            $item_output  .= '<div class="nav-sub-wrap container"><div class="nsw row">';
        }
    }
    $item_output .= $args->after;</code>

The list items on this menu are using the $class_names variable for the custom styling the navigation has. So if IO remove the variable from the li and add it to the the anchor tag, I lose the activate states and everything. Is it somehow possible to avoid that?

I mean the only thing I want is to be able to add different classes like: icon event, icon home etc.. to the 6 different anchor tags on the menu.

回答1:

In your admin area go to Appearance > Menus. On the top right of the screen click on 'Screen Options' on the bottom row - make sure 'CSS Classes' is checked.

In your theme file (where your wp_nav) is you have to add a custom walker.

<?php wp_nav_menu( array('walker' => new Class_Name_Walker ) );?>

In your functions.php - This adds all the classes that are added to the li to all the a as well

class Class_Name_Walker extends Walker_Nav_Menu
    {
        /**
         * Start the element output.
         *
         * @param  string $output Passed by reference. Used to append additional content.
         * @param  object $item   Menu item data object.
         * @param  int $depth     Depth of menu item. May be used for padding.
         * @param  array $args    Additional strings.
         * @return void
         */
         function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

        $class_names = $value = '';

        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;

        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
        $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

        $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
        $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

        $output .= $indent . '<li' . $id . $value .'>';

        $atts = array();
        $atts['title']  = ! empty( $item->attr_title ) ? $item->attr_title : '';
        $atts['target'] = ! empty( $item->target )     ? $item->target     : '';
        $atts['rel']    = ! empty( $item->xfn )        ? $item->xfn        : '';
        $atts['href']   = ! empty( $item->url )        ? $item->url        : '';

        $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );

        $attributes = '';
        foreach ( $atts as $attr => $value ) {
            if ( ! empty( $value ) ) {
                $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
                $attributes .= ' ' . $attr . '="' . $value . '"';
            }
        }
        $item_output = $args->before;
        $item_output .= '<a'. $attributes .$class_names.'>';
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= '</a>';
        $item_output .= $args->after;

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }

    /**
     * @see Walker::end_el()
     * @since 3.0.0
     *
     * @param string $output Passed by reference. Used to append additional content.
     * @param object $item Page data object. Not used.
     * @param int $depth Depth of page. Not Used.
     */
    function end_el( &$output, $item, $depth = 0, $args = array() ) {
        $output .= "</li>\n";
    }
    }


回答2:

If you really want a bare-bones navigation with your own classes in the anchor and you're not bothered about additional classes or sub-navigation, then here's an easier method:

<nav>
    <ul>
    <?php
        $nav = wp_get_nav_menu_items( 'main-navigation' );
        foreach ( $nav as $nav_item ) {
            echo '<li><a href="' . $nav_item->url . '" class="' . implode(' ', $nav_item->classes) . '">' . $nav_item->title . '</a></li>';
        }
    ?>
    </ul>
</nav>


标签: wordpress