Adding bootstrap 4 classes to the WordPress menu

  • Tutorial

Many people already want to use the capabilities of bootstrap 4 when creating websites on WordPress. The following describes one of the solutions for creating menus using the bootstrap 4
classes . The classes for navbar in bootstrap 4 are different from bootstrap 3.


Bootstrap 3



Bootstrap 4



If you use bootstrap 3 in WordPress, you can limit yourself to adding to the wp_nav_menuargument 'menu_class' => 'nav navbar-nav'. If using bootstrap 4, a little more movement is required.



The proposed method is definitely not the only one, but it works.


New wp_bootstrap_navwalker


Download or create a WordPress file in your theme folder wp_bootstrap_navwalker.php.
Repository: https://github.com/sebakerckhof/wp-bootstrap-navwalker
In my case, the file was created in the ./srctheme folder .


For standard WordPress functions.phpthemes, add the line in your theme file


require_once('./src/wp_bootstrap_navwalker.php');

For topics based on the Sage starter theme, the file link will need to be added toincludes


$sage_includes = [
    'src/helpers.php',
    'src/setup.php',
    'src/filters.php',
    'src/admin.php',
    'src/wp-bootstrap-navwalker.php'
];

Change the function wp_nav_menuin the file header.phpas follows


 'primary',
      'theme_location'    => 'primary',
      'depth'             =>  2,
      'container'         => 'div',
      'container_class'   => 'collapse navbar-collapse',
      'container_id'      => 'bs-example-navbar-collapse-1',
      'menu_class'        => 'nav navbar-nav',
      'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
      'walker'            =>  new wp_bootstrap_navwalker())
  );
?>

Now before displaying the menu, a 'walker' will be processed, which will add the necessary classes to the menu.




To create a drop-down list in the menu in the admin panel, Title Attributespecify a value dropdown-header, and a URLvalue #.


If after that the link in the menu is displayed below the rest, then try using a modified script. You can take it here:
https://github.com/eustatos/wp-bootstrap-navwalker .


Menu Icons


This script also supports the creation of icons in menu items. To do this, specify the class of the desired icon in Title Attribute. If you use font-awesome , then it may be fa fa-home.


Also popular now: