Create Bootstrap WordPress theme with v4 & 5

One of the methods of designing WordPress themes is to use Bootstrap in the WordPress theme. But adding Bootstrap to the WordPress website template and menu has its own challenges, and we will discuss how to add Bootstrap 4 and 5 to the WordPress theme step by step in this tutorial.

Today, the first thing that comes to mind at first glance from the website is its design and beauty. In website design, items such as page structure and layout, color scheme, images, etc. before the content of the website attract the user.

There are several platforms on the market, including Bootstrap. With Bootstrap you can create responsive pages easily in less time than from scratch. In this tutorial, we will show you how to create a WordPress theme with Bootstrap 4 and 5.

In this guide, we assume you have a development environment with PHP, MySQL and WordPress installed, and a little knowledge about installation and activating WordPress themes, adding WordPress Menus, creating posts and pages, and theme development.

What is Bootstrap?

Bootstrap is a free platform to develop and design beautiful and responsive templates. It designs a front-end framework that includes a set of HTML and CSS elements for creating custom features such as typography, navigation bars, and buttons, and it also works with a number of optional JavaScript plugins for more functionality with a responsive layout.

The framework became popular because of its lightweight structure as it is coded in LessCSS.

Why use Bootstrap in WordPress?

As we said, using Bootstrap increases the speed of theme development and thus reduces development time and performance. Bootstrap also is an open-source platform created by CSS and JavaScript with a lot of functionality and features. It has classes that will give a special beauty to our design.

The popularity of WordPress and Bootstrap is so great that nearly 30% of the websites on the Internet use WordPress and 3.7% of the websites use Bootstrap to design their own front-end. But using Bootstrap in WordPress isn’t as easy as installing a theme or plugin.

Today, most users use mobile phones or tablets for everyday tasks, and browsing websites is not an exception. Web developers, marketers, and designers understand the huge potential if the website is responsive and can view, navigate, and browse easily on any device, regardless of any resolution and aspect ratio.

Using Bootstrap, you can make any WordPress template responsive so that users can use the website easily. Here are 4 reasons to use Bootstrap:

  1. Bootstrap is a free and open-source framework
  2. Bootstrap is widely used and easy to find useful tutorials and open-source projects
  3. It is quite handy to create responsive websites
  4. Deals with reset, grids, typography, utilities, and media queries

How to add Bootstrap to the WordPress theme?

WordPress themes include HTML, CSS, JavaScript, and PHP code so that anyone with a little knowledge about them can create a template.

Since Bootstrap is created using CSS and JavaScript, it can be easily added to WordPress templates. But this requires a little more effort, and we will explain how to add each version of Bootstrap to WordPress.

By adding Bootstrap to your website, you can invoke its classes to add pre-made elements such as buttons, grids, tables, menus, and more.

ٍEnqueue Bootstrap CSS and JS files in the theme

Adding Bootstrap files to WordPress can be done in two ways:

  1. Upload Bootstrap files to the server and add the files
  2. Using CDN

1 – Uploading Bootstrap files

After downloading Bootstrap, upload files to your server through an FTP program in your theme in “wp-content/themes/your-theme” then unzip Bootstrap files.

This is the standard method to enqueue CSS and JavaScript files in the “functions.php” file. Open “functions.php” of your theme and enqueue Bootstrap style and JavaScript in WordPress.

if (!function_exists('hs_enqueue_scripts')) {
    function hs_enqueue_scripts()
    {
        /* css styles */
        wp_enqueue_style('bootstrap', esc_url(get_template_directory_uri() . '/bootstrap/css/bootstrap.min.css'), array(), '1');

        /* javascript */
        wp_enqueue_script('bootstrap-script', esc_url(get_template_directory_uri() . '/bootstrap/js/bootstrap.bundle.min.js'), array('jquery'), '1.0.0', true);
    }

    add_action('wp_enqueue_scripts', 'hs_enqueue_scripts');
}

To function fully as a site builder, Bootstrap needs jQuery, a popular JavaScript library that gives JavaScript cross-browser compatibility and supports its extensive library of plugins.

2 – Using CDN

You can reference them from a Content Delivery Network (CDN).

if (!function_exists('hs_enqueue_scripts')) {
    function hs_enqueue_scripts()
    {
        /* css styles */
        wp_enqueue_style('bootstrap-cdn-css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css');

        /* javascript */
        wp_enqueue_script('bootstrap-cdn-js', 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js', array('jquery'), '1.0.0', true);
    }

    add_action('wp_enqueue_scripts', 'hs_enqueue_scripts');
}

Integrating Bootstrap navigation with the WordPress menu

So far, we can use Bootstrap in our WordPress template, but there is still one step left to complete, and that is to add the Bootstrap menu to the WordPress template.

Adding Bootstrap to the theme is easy but matching Bootstrap and the WordPress menu is a little complicated.

To accomplish the job, we use a WordPress walker class, which lets developers traverse tree-like data structures with a view to rendering HTML markup. For this tutorial, we are going to use Dominic Businaro’s BS4navwalker, which is freely available on GitHub.

Copy bs4navwalker.php in the root directory of your theme. Add the code to your “functions.php” file.

require_once('bs4navwalker.php');

In WordPress, we use the wp_nav_menu () function to add menus to our theme. In Bootstrap it is a little different. We have to introduce the fallback function and walker class to the WordPress menu as follows.

<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
  <a class="navbar-brand" href="#">
    <?php bloginfo('name'); ?>
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <?php
    wp_nav_menu([
      'menu'            => 'primary',
      'theme_location'  => 'menu-1',
      'container'       => 'div',
      'container_id'    => 'navbarCollapse',
      'container_class' => 'collapse navbar-collapse',
      'menu_id'         => false,
      'menu_class'      => 'navbar-nav mr-auto',
      'depth'           => 0,
      'fallback_cb'     => 'bs4navwalker::fallback',
      'walker'          => new bs4navwalker()
    ]);
  ?>
</nav>

The depth parameter’s value indicates how many hierarchical levels we want to have in our menu. We’ve set this to 0, which is the default value and stands for all.

The walker parameter is here very important, and we’ve set it to a new instance of the bs4navwalker class, which is responsible for rendering the Bootstrap navigation markup.

Bootstrap 5 navigation with the WordPress menu

Download the walker class from here for Bootstrap 5 to integrate with the WordPress menu. Copy the walker to your theme.

Open “functions.php” of your theme and add the below code.

if (!function_exists('hs_setup')) :
    function hs_setup()
    {
        require_once get_template_directory() . '/inc/class-wp-bootstrap-navwalker.php';
    }
    add_action('after_setup_theme', 'hs_setup');
endif;

add_filter( 'nav_menu_link_attributes', 'bootstrap5_dropdown_fix' );
function bootstrap5_dropdown_fix( $atts ) {
     if ( array_key_exists( 'data-toggle', $atts ) ) {
         unset( $atts['data-toggle'] );
         $atts['data-bs-toggle'] = 'dropdown';
     }
     return $atts;
}

In this code, we add the Walker class to our theme and modify it for use in Bootstrap 5. To change the normal WordPress menu to the Bootstrap 5 menu, use the following code.

<nav class="navbar navbar-expand-md" role="navigation">
    <button class="navbar-toggler mobile-btn rounded-circle" type="button" data-bs-toggle="collapse" data-bs-target="#hscollapse" aria-controls="hscollapse" aria-expanded="false" aria-label="Toggle navigation">
        <i class='fas fa-ellipsis-v'></i>
    </button>
    <div id="hscollapse" class="navbar-box collapse navbar-collapse">
        <div class="close navbar-toggler rounded-circle md-invisible d-flex justify-content-center align-items-center" data-bs-toggle="collapse" data-bs-target="#bscollapse" aria-controls="bscollapse" aria-expanded="false" aria-label="Toggle navigation">
            <i class='fas fa-times'></i>
        </div>
        <?php
        wp_nav_menu(array(
           'theme_location'    => 'main-menu',
           'container'         => 'div',
           'menu_class'        => 'nav navbar-nav',
           'fallback_cb'       => 'WP_Bootstrap_Navwalker::fallback',
           'walker'            => new WP_Bootstrap_Navwalker(),
       ));
       ?>
    </div>
</nav>

The above code includes extra buttons for Mobile Button Toggler and Close Menu Button.

We now have a bootstrap menu in WordPress, but there is a bit of a problem with the submenu. The submenu in mobile mode is not clickable for display. To make it clickable, create a javascript file and insert the custom.js file into your project.

Open “functions.php” files and add the below code in it.

if (!function_exists('hs_custom_enqueue_scripts')) {
    function hs_custom_enqueue_scripts()
    {
        wp_enqueue_script('hs-custom-script', esc_url(get_template_directory_uri() . '/assets/js/custom.js'), array('jquery'), '1.0.0', true);
    }

    add_action('wp_enqueue_scripts', 'hs_custom_enqueue_scripts');
}

Open the “custom.js” file and add the below code.

jQuery(document).ready(function() {
    if (window.innerWidth < 768) {
        jQuery(
            ".navbar-nav .menu-item-has-children > a"
        ).click(function(e) {
            e.preventDefault();
            var sub_menu = this.parentNode.querySelector(".dropdown-menu");
            if (sub_menu.className == "dropdown-menu show") {
                this.classList.remove("show");
                sub_menu.classList.remove("show");
            } else {
                this.classList.add("show");
                sub_menu.classList.add("show");
            }
        });

        let dropdowns = document.querySelectorAll(".dropdown-toggle");
        dropdowns.forEach((dd) => {
            dd.addEventListener("click", function(e) {
                var el = this.nextElementSibling;
                el.style.display = el.style.display === "block" ? "none" : "block";
            });
        });
    }
});

Your menu is ready. Now it is time to add some style.

.dropdown-submenu {
    position: relative;
}

.dropdown-menu .menu-item-has-children>.dropdown-menu {
    top: 0;
    left: 100%;
}

.dropdown-submenu:hover>.dropdown-menu {
    display: block;
}

.dropdown-submenu>a:after {
    display: block;
    content: " ";
    float: right;
    width: 0;
    height: 0;
    border-color: transparent;
    border-style: solid;
    border-width: 5px 0 5px 5px;
    border-left-color: #ccc;
    margin-top: 5px;
    margin-right: -10px;
}

.dropdown-submenu:hover>a:after {
    border-left-color: #fff;
}

.dropdown-submenu.pull-left {
    float: none;
}

.dropdown-submenu.pull-left>.dropdown-menu {
    left: -100%;
    margin-left: 10px;
    -webkit-border-radius: 0;
    -moz-border-radius: 0;
    border-radius: 0;
}

Shopping Cart