Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extended Walker_Page doesn’t output custom start_lvl() or end_lvl()

Tags:

php

wordpress

I have a custom Walker_Page class that I have extended like this:

class List_Nav extends Walker_Page {
  function start_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class='ListNav'>\n";
  }

  function start_el(&$output, $page, $depth = 0, $args = array(), $current_page = 0) {
    $output .= '<li class="ListNav-item">';
    $output .= '<a class="ListNav-link" href="' . get_permalink($page->ID) . '">' . apply_filters( 'the_title', $page->post_title, $page->ID ) . '</a>';
    $output .= '</li>';
  }

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

But I’m not getting any output from the start_lvl or end_lvl functions. Is there something I’m missing here or that I need to return? I’m getting the <li> output from start_el().


Update with usage

Here’s how I’m using the walker:

if ($post->post_parent) {
  $ancestors=get_post_ancestors($post->ID);
  $root = count($ancestors) - 1;
  $top_parent = $ancestors[$root];
} else {
  $top_parent = $post->ID;
}

$page_list_args = array(
  'child_of'     => $top_parent,
  'depth'        => 0,
  'title_li'     => false,
  'walker'       => new List_Nav
);

wp_list_pages($page_list_args);
like image 274
Vincent Orback Avatar asked Oct 19 '22 19:10

Vincent Orback


1 Answers

Looks like start_lvl() and end_lvl() is always called within the loop and never on a first level. This goes for all WordPress Walkers like Walker_Nav_Menu, Walker_Page and Walker_Category.

It’s not super clear but you could guess it when you look at the Core Walker code or when you read the Walker documentation about start_lvl().

But in the documentation for Walker::start_lvl it just says that it...

Starts the list before the elements are added.

So perhaps what should be done is an update in the docs.

like image 166
Vincent Orback Avatar answered Oct 31 '22 01:10

Vincent Orback