I’m trying to add a class to anchor links of children element in wp_nav_menu both for pages and posts.
Is there a way to modify the Nav Menu Walker and do so?
Basically my custom walker looks like this:
class Main_Nav extends Walker_Nav_Menu {
function start_lvl(&$output, $depth) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"dropdown-menu\">\n";
}
function start_el(&$output, $item, $depth, $args) {
if( $depth == 0) {
$output .= "<li class="menu">";
}
if( $depth == 1) {
$output .= "<li>";
}
$attributes="";
! empty( $item->attr_title ) and $attributes .= ' title="' . esc_attr( $item->attr_title ) .'"';
! empty( $item->target )and $attributes .= ' target="' . esc_attr( $item->target ) .'"';
! empty( $item->xfn )and $attributes .= ' rel="' . esc_attr( $item->xfn ) .'"';
! empty( $item->url )and $attributes .= ' href="' . esc_attr( $item->url ) .'"';
$title = apply_filters( 'the_title', $item->title, $item->ID );
if (/* THE MENU ELEMENT HAS CHILDREN */) {
$item_output =
"<a $attributes class="menu">"
. $title
. '</a> ';
}
else {
$item_output =
"<a $attributes>"
. $title
. '</a> ';
}
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth);
}
}
As you see I don’t know what the proper condition instead of /* THE ELEMENT HAS CHILDREN */
.
Thank you.
UPDATE
Thanks to Tamil I updated the code as follows:
class Main_Nav extends Walker_Nav_Menu {
function start_lvl(&$output, $depth) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"dropdown-menu\">\n";
}
function start_el(&$output, $item, $depth, $args) {
if( $depth == 0) {
$output .= "<li class="menu">";
}
if( $depth == 1) {
$output .= "<li>";
}
$attributes="";
! empty( $item->attr_title ) and $attributes .= ' title="' . esc_attr( $item->attr_title ) .'"';
! empty( $item->target )and $attributes .= ' target="' . esc_attr( $item->target ) .'"';
! empty( $item->xfn )and $attributes .= ' rel="' . esc_attr( $item->xfn ) .'"';
! empty( $item->url )and $attributes .= ' href="' . esc_attr( $item->url ) .'"';
$title = apply_filters( 'the_title', $item->title, $item->ID );
global $wpdb;
$query = $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status="publish" AND post_type="nav_menu_item" AND post_parent=%d", $item->ID);
$child_count = $wpdb->get_var($query);
if($child_count > 0) { /* THE MENU ELEMENT HAS CHILDREN */
$item_output =
"<a $attributes class="menu">"
. $title
. '</a> ';
} else {
$item_output =
"<a $attributes>"
. $title
. '</a> ';
}
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth);
}
}
No luck though 🙁