作为wordpress初学者。我正在创建菜单也想要自定义<li>
标签,以便能够通过CSS分配不同的类名来控制特定的行为,所以我使用custom walker
获取一个带有干净标记的列表,我在这里找到:
https://gist.github.com/toscho/1053467
class T5_Nav_Menu_Walker_Simple 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
*/
public function start_el( &$output, $item, $depth, $args )
{
$output .= '<li>';
$attributes = '';
! empty ( $item->attr_title )
// Avoid redundant titles
and $item->attr_title !== $item->title
and $attributes .= ' title="' . esc_attr( $item->attr_title ) .'"';
! empty ( $item->url )
and $attributes .= ' href="' . esc_attr( $item->url ) .'"';
$attributes = trim( $attributes );
$title = apply_filters( 'the_title', $item->title, $item->ID );
$item_output = "$args->before<a $attributes>$args->link_before$title</a>"
. "$args->link_after$args->after";
// Since $output is called by reference we don't need to return anything.
$output .= apply_filters(
'walker_nav_menu_start_el'
, $item_output
, $item
, $depth
, $args
);
}
/**
* @see Walker::start_lvl()
*
* @param string $output Passed by reference. Used to append additional content.
* @return void
*/
public function start_lvl( &$output )
{
$output .= '<ul class="sub-menu">';
}
/**
* @see Walker::end_lvl()
*
* @param string $output Passed by reference. Used to append additional content.
* @return void
*/
public function end_lvl( &$output )
{
$output .= '</ul>';
}
/**
* @see Walker::end_el()
*
* @param string $output Passed by reference. Used to append additional content.
* @return void
*/
function end_el( &$output )
{
$output .= '</li>';
}
}
代码完美无缺。但现在,当我想通过“ Css类”在菜单中的一个项目中添加可选类时,但它不起作用。
答案 0 :(得分:0)
如果您只想将一个类添加到一个或多个菜单项中,那么您可能很难做到这一点。
使用“nav_menu_css_class”过滤器,而不是使用自定义Walker。类似的东西:
function my_special_nav_class( $classes, $item ) {
// Decide if you want to add a class and add it to array $classes
return $classes;
}
add_filter( 'nav_menu_css_class', 'my_special_nav_class', 10, 2 );
答案 1 :(得分:0)
只需将类名放在li
中public function start_el( &$output, $item, $depth, $args ){
$output .= '<li class="YourCustomClassHere">';
$attributes = '';
! empty ( $item->attr_title )
// Avoid redundant titles
and $item->attr_title !== $item->title
and $attributes .= ' title="' . esc_attr( $item->attr_title ) .'"';
! empty ( $item->url )
and $attributes .= ' href="' . esc_attr( $item->url ) .'"';
$attributes = trim( $attributes );
$title = apply_filters( 'the_title', $item->title, $item->ID );
$item_output = "$args->before<a $attributes>$args->link_before$title</a>"
. "$args->link_after$args->after";
// Since $output is called by reference we don't need to return anything.
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}