首先,您可以使用 Walker。
创建新类,您需要一个名为 start_el 的函数(您可以在 wp-includes/class-walker-nav-menu.php 中找到它)。最简单的方法就是复制它。您需要更改 $item_output
class Your_Walker extends Walker_Nav_Menu {
public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
// Code here
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
$item_output .= $args->link_before . $title . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
}
}
您可以提及锚标记及其内部的 $title(链接标题)。您可以将 $title 包装到 span 中并将其加倍,如下所示:
class Your_Walker extends Walker_Nav_Menu {
public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
// Code here
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
$item_output .= $args->link_before . '<span>' . $title . '</span>' . $args->link_after;
$item_output .= $args->link_before . '<span>' . $title . '</span>' . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
}
}
注意 $args->link_before/after 可以通过调用 wp_nav_menu 来使用,并且不需要添加额外的 span(我将在下面解释)。
第二种方式:有点棘手但更简单,它会起作用。像这样调用 wp_nav_menu:
wp_nav_menu(array(
'theme_location' => 'your_location',
'link_before' => '<span>', // This will wrap your title
'link_after' => '</span>',
));
在你的functions.php中
function add_double_span_to_menu( $item_output, $item, $depth, $args ){
// replace closing '</a>' with '<span>Links Title</span></a>'
$replace = $args->link_before . $item->title . $args->link_after . '</a>';
$item_output = str_replace('</a>', $replace, $item_output);
return $item_output;
}
add_filter('walker_nav_menu_start_el', 'add_double_span_to_menu', 10, 4);