WordPress自定义菜单函数警告提示:Declaration of description_walker

导语:叶子在制作一款WordPress主题时,希望菜单可以自定义一些内容,于是就在网络上面找了一段代码,复制到functions.php里面,结果打开页面时出现了警告:Declaration of description_walker::start_el(&$output, $item, $depth, $args) should be compatible with Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) 。

网络上的代码示例

为了让大家更加清楚这个警告的情况,叶子把网上的代码也粘贴出来:


function register_menus() {
register_nav_menus( array( 'top-menu' => 'Top primary menu')
                    );

} add_action('init', 'register_menus');

class description_walker extends Walker_Nav_Menu { 
      function start_el(&$output, $item, $depth, $args) { 
      global $wp_query; 
      $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

       $class_names = $value = '';

       $classes = empty( $item->classes ) ? array() : (array) $item->classes;

       $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
       $class_names = ' class="'. esc_attr( $class_names ) . '"';

       $output .= $indent . '

执行后出现:Declaration of description_walker::start_el(&$output, $item, $depth, $args) should be compatible with Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) 。

原因分析

原因很简单,其实这段代码在低级版本中使用是没有问题的,WordPress的高级版本重新定义了start_el()函数,它增加了新的参数,所以就出现了警告,在高级版本使用时,重新定义一下start_el()函数就可以了。

解决方法

将两处替换就可以了,如下所示:

  • function start_el(&$output, $item, $depth, $args)
    

    替换为

    function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0)
    
  • $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args);
    

    替换为

    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args, $id );
    

注意到了吗?$depth = 0,$args = array(),$id = 0,这三个参数和原来不样了。

结束

你学会了吗?其实就是自定义菜单在高一点的版本中改名了定义的方式,所以,你从低一点版本复制过来的代码要修改一下才能适应新的版本。

目前在“WordPress自定义菜单函数警告提示:Declaration of description_walker”上有2条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注