Search code examples
phpwordpresswordpress-theming

How to use walker to replace core function


I want to modify the way pages are listed in the navigation, particularly the function el_start from wp-includes/classes.php.

I've first modified the classes.php directly and it worked fine butnow I want to revert classes.php and move the modification out of wordpress' internal files.

I wrote a walker class that I want to use but I don't know how to use it. I want to replace the current call wp_list_pages() to this:

 $walker_pages = new Walker_Page_CustomTitle;
 wp_list_pages(array('walker' => $walker_pages, 'title_li' => '', 'depth' => '1'));

I've tried using a filter like so:

function wp_list_pages_custom() {
     $walker_pages = new Walker_Page_CustomTitle;
     wp_list_pages(array('walker' => $walker_pages, 'title_li' => '', 'depth' => '1'));
}
add_filter('widget_area_primary_aside', 'wp_list_pages_custom');

But with this filter, the site won't load anymore.

The tutorial here says I should put this code in header.php but that just puts my page links in the tag.

I hope I'm making sense. Thanks.


Solution

  • It would be ideal if wp_list_pages() had a filter on the passed arguments, before it executed any further code.

    However, the best approach I can see, whereby simply using wp_list_pages() without passing a walker argument uses your walker is like so;

    function my_custom_wp_pages($list, $args)
    {
        $walker = new Walker_Page_CustomTitle;
        $args = array_merge($args, array('walker' => $walker, 'echo' => false);
    
        remove_filter('wp_list_pages', 'my_custom_wp_pages'); // avoid endless loop
    
        $list = wp_list_pages($args);
    
        add_filter('wp_list_pages', 'my_custom_wp_pages'); // add it back
    
        return $list;
    }
    add_filter('wp_list_pages', 'my_custom_wp_pages', 5, 2);
    

    UPDATE:

    Edited the add_filter call to accept two arguments.