开发者

Replacing WordPress core functionality with a plugin

开发者 https://www.devze.com 2023-03-23 09:54 出处:网络
I\'m creating a WordPress plugin for a custom menu layout. I am well aware that I could just as easily implement this menu directly into the theme and I\'ve read up quite thoroughly on the features an

I'm creating a WordPress plugin for a custom menu layout. I am well aware that I could just as easily implement this menu directly into the theme and I've read up quite thoroughly on the features and limitations of wp_nav_menu(), plus I have already tried and tested every plugin already created for replacing the default WordPress menu.

I wish to use a plugin since my client will be implementing this on several different WordPress sites, many of which run on different themes - and most of those are themes which I did not create and I do not wish to re-write their code in case they update the theme in the future.

When I've looked into a way to implement the menu into the theme I found that there are only two good methods since there is no hook or filter called at menu display time. The first is to change the theme to look for the plugin (this is similar to the method used by PixoPoint and many other menu plugins):

header.php:

if(function_exists('pixopoint_menu')){
    pixopoint_menu();
} else {
    wp_nav_menu();
}

The second method is a walker class:

plugin.php:

class my_walker_class Extends Walker_Nav_Menu {
    function start_el(&$output, $item, $depth, $args) {
        /*
        *  Etc. Etc.
  开发者_高级运维      */
    }
}

header.php:

wp_nav_menu( Array( 'walker' => 'my_walker_class' ) );

However as you'll note both of these methods require a modification to the standard header.php file.

Ideally I would like to simply replace the wp_nav_menu() function if my plugin is loaded, as this would give my plugin support for the majority of themes without having to edit any of the theme files. Is there a good way to do this? Or is there a better way to write a menu plugin which I am not seeing?


You can use the wp_nav_menu_args filter to modify the arguments passed to wp_nav_menu, so you can specify your custom walker class.

add_filter('wp_nav_menu_args', 'my_wp_nav_menu_args_filter');
function my_wp_nav_menu_args_filter($args = array()) {
  $args['walker'] = new my_walker_class();
  return $args;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号