Cómo agregar <span> a cada enlace de menú con el texto del enlace en un atributo data

1 feb 2016, 08:08:35
Vistas: 19.5K
Votos: 9

¿Cómo puedo obtener algo como lo siguiente? Mi código es así:

wp_nav_menu(
     array(
       'theme_location' => 'header_menu',
       'container_id' => 'menu',
       'link_before' => '<span data-hover="link-text-here">',
       'link_after' => '</span>',
     )
  );

Quiero obtener el siguiente resultado:

<nav class="main-nav">
    <li><a href="#"><span data-hover="Home">Home</span></a></li>
    <li><a href="#"><span data-hover="Proyects">Proyects</span></a></li>
</nav>

Por favor, aconséjame.

0
Todas las respuestas a la pregunta 3
2
14

Desde la versión 4.4.0 se añadió el filtro 'nav_menu_item_args'. Esto te permite establecer los atributos 'link_before' y 'link_after' para cada elemento del menú.

add_filter('nav_menu_item_args', function ($args, $item, $depth) {
    if ($args->theme_location == 'header_menu') {
        $title             = apply_filters('the_title', $item->title, $item->ID);
        $args->link_before = '<span data-hover="' . $title . '">';
        $args->link_after  = '</span>';
    }
    return $args;
}, 10, 3);
9 jun 2018 13:26:31
Comentarios

Eso no es correcto... a continuación está la salida después de usar el filtro...

<li id="menu-item-44" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-24 current_page_item menu-item-44">
    <a href="http://sandbox.test/about/" aria-current="page">
        <span data-hover="About">About</span>
    </a>
</li>
Daren Zammit Daren Zammit
12 abr 2019 10:07:17

gracias. tu código funciona para mí

Younes.D Younes.D
31 jul 2021 11:52:19
4

Solución 1: Usando un walker personalizado

Obtuve algunas ideas de añadir clase span dentro de la etiqueta de anclaje de wp_nav_menu e hice algunos cambios para tus requisitos.

1. Primero añade este código a tu functions.php.

class Nav_Walker_Nav_Menu extends Walker_Nav_Menu{
  function start_el(&$output, $item, $depth, $args){
       global $wp_query;
       $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        ) .'"' : '';

       $description  = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';

        $item_output = $args->before;
        $item_output .= '<a'. $attributes .'><span data-hover="'. $item->title .'">';
        $item_output .=$args->link_before .apply_filters( 'the_title', $item->title, $item->ID );
        $item_output .= $description.$args->link_after;
        $item_output .= '</span></a>';
        $item_output .= $args->after;

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

2. Añade el código a continuación a tu header.php donde esté instalado tu wp_nav_menu. Explicado a continuación está el código para que instale el nuevo menú personalizado, en este caso sería Nav_Walker_Nav_Menu.

<?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary', 'walker' => new Nav_Walker_Nav_Menu() ) ); ?>

¡Espero que esto te ayude!

Solución 2: Usando wp_list_pages

Por favor revisa esta página. Puedes ver su fragmento de código. Si pones los spans alrededor de las etiquetas de enlace puedes usar link_before y link_after

wp_list_pages("link_before=<span data-hover="link-text-here">&link_after=</span>");
1 feb 2016 08:17:14
Comentarios

dice

Aviso: Intentando obtener propiedad de un objeto no definido en /Applications/MAMP/htdocs/wp.dev/wp-content/themes/eta-theme/functions.php en la línea 98

Mohamed Rihan Mohamed Rihan
1 feb 2016 10:00:06

Entonces, ¿cuál es el código en la línea 98?

AddWeb Solution Pvt Ltd AddWeb Solution Pvt Ltd
1 feb 2016 10:02:46

$item_output = $args->before; $item_output .= '<a'. $attributes .'><span data-hover="'. $item->title .'">'; $item_output .=$args->link_before .apply_filters( 'the_title', $item->title, $item->ID ); $item_output .= $description.$args->link_after; $item_output .= '</span></a>'; $item_output .= $args->after;

Mohamed Rihan Mohamed Rihan
1 feb 2016 10:08:01

parece estar bien ahora. es porque no agregué el menú en el panel de control.. gracias

Mohamed Rihan Mohamed Rihan
1 feb 2016 10:08:54
1

Por favor, prueba lo siguiente:

wp_nav_menu(
 array(
   'theme_location' => 'header_menu',
   'container_id' => 'menu',
   'walker' => new description_walker()
 )
);

Y agrega esto a functions.php:

class description_walker extends Walker_Nav_Menu{
  function start_el(&$output, $item, $depth, $args){
       global $wp_query;
       $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        ) .'"' : '';


       $description  = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';



        $item_output = $args->before;
        $item_output .= '<a'. $attributes .'><span>';
        $item_output .=$args->link_before .apply_filters( 'the_title', $item->title, $item->ID );
        $item_output .= $description.$args->link_after;
        $item_output .= '<span></a>';
        $item_output .= $args->after;

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

De esta manera puedes agregar fácilmente una etiqueta span...

1 feb 2016 08:17:28
Comentarios

pero quiero el atributo data dentro del span

Mohamed Rihan Mohamed Rihan
1 feb 2016 09:15:02