You are on page 1of 82

Beginners Guide To WordPress Menus & Bootstrap Navigation

Learn how to use Bootstrap's navigation with WordPress Menus.


20th August 2016

Twitter Bootstrap is an incredibly popular front-end framework due to its ease of use and the speed in
which you can get a web application up and running. Its no surprise that many WordPress themes are
now being built with Bootstrap; however, getting the WordPress menu editor to work with Bootstraps
default navigation isnt as simple as just including the relevant Bootstrap CSS and JavaScript files. With
the help of some navigation walkers, we can get WordPress menus and Bootstrap navigation working
harmoniously together.
Please note, if you are working on an existing theme, then please do make a backup of your themes files
in case anything goes wrong.
Actually Creating a Menu
Before we can start thinking about getting the Bootstrap navigation to work, we need to make sure we
actually have a menu we can use. If you already have a menu set up in your WordPress admin, then you
can skip this part and move on to including the required Bootstrap files into your theme, otherwise read
on.
Register a Menu
First things first, we need to register the name of our menu. Open up the functions.php file of your theme
and add the following code:
function register_header_menu() {
register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'register_header_menu' );

Defining Your Menu

We now need to define a menu within the WordPress Menu Editor. Go ahead and login to your admin and
go to Appearance > Menus.
Click on the text field Menu Name and name your new menu. This can be anything you want, but it
should really be something that makes sense regarding the items are included in the menu.

Add Items to Your Menu


Add some items to your menu using the various options on the left. Once you have finished adding all of
the items you would like to your menu, tick the checkbox Bootstrap Menu under menu locations and
then click Save Menu. Your menu is now created and linked with a menu location.
If you would like to know more about using the WordPress menu editor, then you can read the official
documentation here.
Including Twitter Bootstrap into Your WordPress Theme
If were going to be using the Twitter Bootstrap navigation then we will need to include the relevant files
within our theme. There are a number of ways to do this; we can either use the Bootstrap JavaScript and
CSS files hosted on CDNs or we can download the files and save them within our themes files.
You can download the Bootstrap files at getbootstrap.com or you can use the following CDN hosted files:
Required Bootstrap CSS file

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"


integrity="sha384-
1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
An optional Bootstrap theme CSS file
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-
theme.min.css" integrity="sha384-
fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
Required Bootstrap JavaScript file
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-
0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous">
If you really want to, you can simply include these files directly within your template files, e.g. the styles
within the document head in your header.php file and the JavaScript file before the closing body tag in
your footer.php file; however, its recommended to do this the WordPress way by enqueuing these styles
and scripts. You can read the official WordPress documentation about enqueuing styles and scripts here.
To enqueue these files you will need to edit your functions.php file. If you want to use the Bootstrap
CDNs use the following code snippet:
// The CSS files for your theme
function theme_styles() {
wp_enqueue_style('bootstrap-css',
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css', array(), '', 'all');
wp_enqueue_style('bootstrap-theme', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-
theme.min.css', array('bootstrap-css'), '', 'all');
}

// The JavaScript files for your theme


function theme_js() {
wp_enqueue_script( 'bootstrap-js',
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js', array('jquery'), '', true );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );


add_action( 'wp_enqueue_scripts', 'theme_js' );
If these files are hosted on your own domain, e.g. within /js/ and /css/ directories within your theme, then
you can load them like so:
// The CSS files for your theme
function theme_styles() {
wp_enqueue_style('bootstrap-css', get_template_directory_uri . '/css/bootstrap.min.css', array(), '', 'all');
wp_enqueue_style('bootstrap-theme', get_template_directory_uri . '/css/bootstrap-theme.min.css',
array('bootstrap-css'), '', 'all');
}

// The JavaScript files for your theme


function theme_js() {
wp_enqueue_script( 'bootstrap-js', get_template_directory_uri . '/js/bootstrap.min.js', array('jquery'), '',
true );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );


add_action( 'wp_enqueue_scripts', 'theme_js' );
We have used the get_template_directory_uri() function here to return your themes URL. If you are using
a child theme and the Bootstrap CSS and JavaScript files are stored there, you will want to
use get_stylesheet_directory_uri() instead to return the child themes URL.
Save your functions.php file and then reload any page on your site. You should now see the Bootstrap
CSS files loading in the document head and the JavaScript Bootstrap file loading just before the closing
body tag.
With that complete were ready to begin making Bootstraps navigation work with WordPress menus.
Bootstrap Nav Walker for WordPress
Out of the box Twitter Bootstrap doesnt work with WordPress menus. To get the two working well
together, your theme will require a walker. Luckily, Edward McIntyre (AKA Twittem) has already created
one that works and is very easy to set up. You can find his Bootstrap Navwalker here.
Including Edward Mcintyres WP Bootstrap Navwalker into Your Theme
Download the ZIP file of WP Bootstrap Navwalker from GitHub and extract this file. Copy and paste the
wp_bootstrap_navwalker.php file into your themes main directory. We then need to include this PHP file
in our functions.php before we actually do anything with our menus.
Open your functions.php and add this code:
// Register Custom Navigation Walker
require_once('wp_bootstrap_navwalker.php');
Setting up WP Bootstrap Navwalker
We are now going to create a quick function that we can call from within our theme, where we want this
Bootstrap navigation to appear. Just below where we added the above code to include
wp_bootstrap_navwalker.php, add the following lines of code:
// Bootstrap navigation
function bootstrap_nav()
{
wp_nav_menu( array(
'theme_location' => 'header-menu',
'depth' => 2,
'container' => 'false',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'wp_bootstrap_navwalker::fallback',
'walker' => new wp_bootstrap_navwalker())
);
}
What we have done here is add a new argument walker to wp_nav_menu(). This creates a new instance of
the wp_boostrap_navwalker object. You can find out more about wp_nav_menu()over at the official
documentation.
Adding Bootstrap Navigation Markup
Now we need to actually call the bootstrap_nav() function from within our theme. In this scenario we will
be adding this menu to our header.php file. Below is the code that you need to add to your header.php file
where you want the Bootstrap navigation to appear:
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<?php bootstrap_nav(); ?>
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
What you are doing here is adding the markup for Bootstrap navigation and calling the
function bootstrap_nav() that you just created in functions.php. Whatbootstrap_nav() is doing is creating
an unordered list of the WordPress menu items with the correct Bootstrap markup.
N.B. this code should really replace any navigation and logo that you currently have in your header.php
file. Of course you are free to modify this as you see fit, e.g. you may want two menus within your
websites header.
If you now go and reload a page on your site, you should see the new Bootstrap navigation there with the
menu items pulled in from your WordPress menu. Excellent!

If you want to have a dropdown of menu items, go back to the WordPress menu editor and drag the child
menu items below the desired parent menu item. Save this menu and then reload the page on your site and
you should now see a dropdown menu. Please note that Bootstrap 3 does not support dropdown sub-
menus.
How about we take this one step further and look at creating Bootstrap mega menus that work with
WordPress menus?
Bootstrap Mega Menus for WordPress
Bootstraps navigation now works with WordPress menus, but how do we go about creating mega menus
with this set up? Well, there is a great project on GitHub called YAMM 3 which makes it really simple to
create mega menus for Bootstrap.
YAMM Nav Walker for YAMM 3
For us to get the markup right for the navigation to use YAMM 3, we need to include another nav walker.
For this we can use Ryan McDonalds YAMM Nav Walker which you can download here.
Including Ryan Mcdonalds YAMM Nav Walker in WordPress
Including YAMM Nav Walker is a straightforward process and exactly the same as how we added Edward
McIntyres WP Bootstrap Navwalker. Download the ZIP file of YAMM Nav Walker and copy and paste
the yamm-nav-walker.php file into the main directory of your theme.
Edit your themes functions.php file where we used the require_once() function for
wp_bootstrap_navwalker.php and change it to this:
// Register WP Bootstrap Navwalker
require_once('wp_bootstrap_navwalker.php');

// Register YAMM Navigation Walker


require_once('yamm-nav-walker.php');
Setting up YAMM Nav Walker
Now we have YAMM Nav Walker included in our themes functions.php file, we need to make use of this
new navigation walker. Just below where we added thebootstrap_nav() function in our functions.php file,
add the following code:
// Bootstrap mega menu navigation
function bootstrap_megamenu_nav()
{
wp_nav_menu( array(
'theme_location' => 'header-menu',
'depth' => 4,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bootstrap-navbar-collapse-1',
'menu_class' => 'nav navbar-nav yamm',
'fallback_cb' => 'Yamm_Nav_Walker_menu_fallback',
'walker' => new Yamm_Nav_Walker())
);
}
We now have a menu setup to create an instance of the Yamm_Nav_Walker object instead of
the wp_bootstrap_navwalker object.
Add Another Level of Items to Your Menu
In the WordPress Menu Editor add another level of menu items to your menu and click Save Menu. These
will be the lists of links within your mega menu.

Including YAMM 3 for WordPress


Download the ZIP file for YAMM 3 here, then copy and paste the yamm.css file into the directory where
you have all of the CSS files in your theme e.g. /yourtheme/css/. We can now include this CSS file in our
theme by using wp_enqueue_styles().
Open your themes functions.php file and edit the theme_css() function we created earlier to also include
yamm.css:
// The CSS files for your theme
function theme_styles() {
wp_enqueue_style('bootstrap-css', get_template_directory_uri . '/css/bootstrap.min.css', array(), '', 'all');
wp_enqueue_style('bootstrap-theme', get_template_directory_uri . '/css/bootstrap-theme.min.css',
array('bootstrap-css'), '', 'all');
wp_enqueue_style('yamm', get_template_directory_uri . '/css/yamm.css', array('bootstrap-theme'), '',
'all');
}
Save your functions.php file and then refresh a webpage of your site. You should now see yamm.css being
included within the source code.
Setting up YAMM 3
You can view a demo of YAMM 3 here to see the various types of mega menu you can create. In our
example, if you go into your WordPress admin and create a multi-level menu down to 3 levels, youll see
that it doesnt look particularly pleasing to the eye. It would probably be best to edit the list styling.
Bootstrap provides us with an easy way to change the list styling just by adding the class list-unstyled to
a ul element. You could go into your yamm-nav-walker.php file and add the class list-unstyled to the
relevant ul element in there; however, this change will get overwritten whenever you update this plugin.
A better option is to simply update your style.css to set the list-style to none. For the ulelements that we
want to style, Yamm Nav Walker has added a classelementy-ul. We can use this class to easily change the
list styling. Open your style.css file and create the following CSS rule:
.yamm ul.elementy-ul {
list-style:none;
max-width:120px;
padding-left:0;
}
If you now reload your webpage, you should see that the list items are all nicely aligned on the left
without any bullet points.

Of course, you can style these mega menus however you like. For example, you might want to add a
media query that adds a bottom margin between each of the ulelements when viewing the menu on
mobile:
@media screen and (max-width: 767px) {
.yamm ul.elementy-ul {
margin-bottom:25px;
}
}
Creating a Mega Menu Plugin to Be Used Across Multiple Themes
Ok, so we can create standard WordPress menus with a drop down and Bootstrap and we can create mega
menus with Bootstrap, but what if you wanted to use this across multiple themes quite often? Well instead
of having to copy and paste this code into each themes functions.php file, we can just create a WordPress
plugin.
The following is an example of a really simple plugin you can build to easily integrate Bootstrap
navigation with your WordPress themes.
Create Your Plugin
First things first, we need to create a folder to place all of our plugin files. Go to your plugin directory and
create a folder called bootstrap-nav-megamenu or whichever name you prefer.
Copy and paste the wp_bootstrap_navwalker.php and yamm-nav-walker.php files into this directory.
Create a sub-directory called CSS and copy yamm.css into this directory, then create a file called
bootstrap-nav-megamenu.php in the main directory for this plugin.
In the file bootstrap-nav-megamenu.php add the following block of code:
<?php
defined('ABSPATH') or die("No script kiddies please!");
/*
Plugin Name: Bootstrap Nav Megamenu
Plugin URI: http://www.yourdomain.com/
Description: Easily integrate Bootstrap menus and megamenus with WordPress
Version: 0.1
Author: Your Name
Author URI: http://www.yourdomain.com/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

// Register WP Bootstrap Walker


require_once('wp_bootstrap_navwalker.php');

// Register YAMM Navigation Walker


require_once('yamm-nav-walker.php');

// Bootstrap navigation
function bootstrap_nav()
{
wp_nav_menu( array(
'theme_location' => 'header-menu',
'depth' => 2,
'container' => 'false',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'wp_bootstrap_navwalker::fallback',
'walker' => new wp_bootstrap_navwalker())
);
}

// Bootstrap mega menu navigation


function bootstrap_megamenu_nav()
{
wp_nav_menu( array(
'theme_location' => 'header-menu',
'depth' => 4,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bootstrap-navbar-collapse-1',
'menu_class' => 'nav navbar-nav yamm',
'fallback_cb' => 'Yamm_Nav_Walker_menu_fallback',
'walker' => new Yamm_Nav_Walker())
);
}

// Load YAMM styles


function bootstrap_mega_menu_styles()
{
wp_register_style('yamm', plugin_dir_url(__FILE__) . 'css/yamm.css', array('bootstrap-theme'), '',
'all');
wp_enqueue_style('yamm'); // Enqueue it!
}

add_action('wp_enqueue_scripts', 'bootstrap_mega_menu_styles'); // Add YAMM Stylesheet


This is essentially combining all of the code that we created in the previous sections and placing it within
our plugin. A change we have made here is that we have created two different functions for
creating wp_nav_menu(); one for just a normal Bootstrap navigation and one that uses YAMM mega
menus.
To include either of these navigation menus within your theme; add either of these code snippets where
you would like your navigation to appear.
<?php bootstrap_nav(); ?>
for the standard Bootstrap navigation or
<?php bootstrap_megamenu_nav(); ?>
for the YAMM mega menu.
If you reload your web page after calling one of the above functions in one of your themes templates,
then you should now see your Bootstrap navigation showing up.
Adding Images to Your Mega Menu
We have our Bootstrap mega menu working and we have it set up as a plugin, but it doesnt look
particularly great, as it is just separate lists of text (just text may actually look great depending on how
you style it!). What if we want to add images to each of our menu items? Luckily there is a plugin already
out there that can take care of this for us, Menu Image by Zviryatko.
Download the Menu Image plugin to your plugins directory and activate it. Once you have done this, if
you visit the Menu Editor you should be able to see some new options under each of the menu items in
the menu you have already created.
You can then select an image for each menu item and how that displays on the front-end. Once you have
added some images and saved your menu, go back and reload one of your sites pages. Voila! You should
now see these images appearing alongside your menu items.

Summary
Despite the fact that WordPress menus and Bootstrap navigation dont work together out of the box, there
resources available to make the task of combining the two much simpler. All thats left now is to get
creative and style your WordPress Bootstrap hybrid menu.
Resources
WordPress Menus documentation
Twitter Bootstrap
wp_enqueue_script() documentation
Edward McIntyres WP Bootstrap Navwalker
wp_nav_menu() documenation
Ryan McDonalds YAMM Nav Walker
YAMM 3
Menu Image Plugin

Druga varijanta menija


Have you ever wanted to speed-up the process of theme development? I assume the answer is "yes" and
you already know about Bootstrap and use it in mock-ups for development. This raises the question:
"How can you integrate Bootstrap components into a WordPress theme?"
This series of tutorials will cover integration of most popular Bootstrap components into a WordPress
theme. Let's start with the Navbar component which allows easy creation of a responsive navigation bar.
To keep this tutorial easy to follow I will take a navigation bar which consists of just a logo and menu.
Looking for a Shortcut?
If you need to get this done quickly and reliably, you can find plenty of Bootstrap and WordPress experts
over on Envato Studio who can help you.
Bootstrap experts on Envato Studio
1. Code Your Navigation Bar With the Bootstrap Framework
Here is source code from Bootstrap documentation page:
<nav class="navbar navbar-default" role="navigation">
01 <!-- Brand and toggle get grouped for better mobile display -->
02 <div class="navbar-header">
03 <button type="button" class="navbar-toggle" data-toggle="collapse" data-
04 target=".navbar-ex1-collapse">
05 <span class="sr-only">Toggle navigation</span>
06 <span class="icon-bar"></span>
07 <span class="icon-bar"></span>
08 <span class="icon-bar"></span>
09 </button>
10 <a class="navbar-brand" href="#">Brand</a>
11 </div>
12 <!-- Collect the nav links, forms, and other content for toggling -->
13 <div class="collapse navbar-collapse navbar-ex1-collapse">
14 <ul class="nav navbar-nav">
15 <li class="active"><a href="#">Link</a></li>
16 <li><a href="#">Link</a></li>
17 <li class="dropdown"> <a href="#" class="dropdown-toggle" data-
18 toggle="dropdown">Dropdown <b class="caret"></b></a>
19 <ul class="dropdown-menu">
20 <li><a href="#">Action</a></li>
21 <li><a href="#">Another action</a></li>
22 <li><a href="#">Something else here</a></li>
23 <li><a href="#">Separated link</a></li>
24 <li><a href="#">One more separated link</a></li>
25 </ul>
26 </li>
27 </ul>
28 </div>
</nav>
Let's have a closer look at the code and clarify things for a better understanding of the next part of the
tutorial.
1 <nav role="navigation"></nav>
Wrapper - a <nav> tag with class "navbar" and role "navigation" wraps the whole content of the
navigation bar.
1 <div class="navbar-header"></div>
Header a <div> with class "navbar-header" which is visible on any size screens.
<button class="navbar-toggle" type="button" data-toggle="collapse" data-
1
target=".navbar-ex1-collapse"></button>
Toggle button - a <button> which represents collapsed content on small screens; this button is a must but
you can change content inside it.
1 <a class="navbar-brand" href="#">Brand</a>
Brand a link with the logo; it is optional, you can omit it here and include it elsewhere.
1 <div class="collapse navbar-collapse navbar-ex1-collapse"></div>
Collapsible content - a <div> with class "collapse" and "navbar-collapse"; it contains all content which
should be collapsed on small screens.
1 <ul class="nav navbar-nav"></ul>
Menu a <ul> with class "nav navbar-nav" which represents site navigation.
2. Integrate the Mock-Up Into a Template
This step assumes that you already have WordPress installed and the theme you're developing has been
activated.
2.1. Prepare Your Theme for the Menu
Open your functions.php file and register your navigation if you haven't yet.
<?php
1
/* Theme setup */
2
add_action( 'after_setup_theme', 'wpt_setup' );
3
if ( ! function_exists( 'wpt_setup' ) ):
4
function wpt_setup() {
5
register_nav_menu( 'primary', __( 'Primary navigation', 'wptuts' )
6
);
7
} endif;
8
?>
Register bootstrap files and jQuery:
function wpt_register_js() {
01 wp_register_script('jquery.bootstrap.min', get_template_directory_uri() .
02 '/js/bootstrap.min.js', 'jquery');
03 wp_enqueue_script('jquery.bootstrap.min');
04 }
05 add_action( 'init', 'wpt_register_js' );
06 function wpt_register_css() {
07 wp_register_style( 'bootstrap.min', get_template_directory_uri() .
08 '/css/bootstrap.min.css' );
09 wp_enqueue_style( 'bootstrap.min' );
10 }
add_action( 'wp_enqueue_scripts', 'wpt_register_css' );
Download Edward McIntyre's wp-bootstrap-navwalker class from GitHub. Place the file into theme root
folder. Go back to your functions.php and paste the following code:
1 <?php // Register custom navigation walker
2 require_once('wp_bootstrap_navwalker.php');
3 ?>
2.2. Create a Menu in the Back-End
Navigate to your Wordpress site back-end Appearance->Menu. Create a new menu called "Primary" and
add items to it. Go to tab Manage Locations and for theme location called "Primary" assign the menu
"Primary". Save changes.
Wordpress Menu Management Page

2.3. Integrate Navigation Bar Mock-Up Into a Template

Open your header.php and copy & paste the navigation bar mock-up into the place where you want it to
appear. Now we replace parts of the mock-up with WordPress' template functions. Firstly place the
correct link for the logo. Change this line:
1 <a class="navbar-brand" href="#">Brand</a>
to:
<a class="navbar-brand" href="<?php bloginfo('url')?>"><?php
1
bloginfo('name')?></a>
The next step is to output the menu from the back-end intead of the mock-up Menu. For these lines:
<ul class="nav navbar-nav">
01
<li class="active"><a href="#">Link</a></li>
02
<li><a href="#">Link</a></li>
03
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-
04
toggle="dropdown">Dropdown <b class="caret"></b></a>
05
<ul class="dropdown-menu">
06
<li><a href="#">Action</a></li>
07
<li><a href="#">Another action</a></li>
08
<li><a href="#">Something else here</a></li>
09
<li><a href="#">Separated link</a></li>
10
<li><a href="#">One more separated link</a></li>
11
</ul>
12
</li>
13
</ul>
With:
01 <?php /* Primary navigation */
02 wp_nav_menu( array(
03 'menu' => 'top_menu',
04 'depth' => 2,
05 'container' => false,
06 'menu_class' => 'nav',
07 //Process nav menu using our custom nav walker
08 'walker' => new wp_bootstrap_navwalker())
09 );
10 ?>
Now you have bootstrap Navbar component integrated into your theme.

wp-bootstrap-navwalker
WP Bootstrap Navwalker

A custom WordPress nav walker class to fully implement the Bootstrap 3.0+ navigation style in a custom
theme using the WordPress built in menu manager.
NOTES
This is a utility class that is intended to format your WordPress theme menu with the correct syntax and
classes to utilize the Bootstrap dropdown navigation, and does not include the required Bootstrap JS files.
You will have to include them manually.
Bootstrap 4
Bootstrap 4 beta is available and is now the default branch offered at the GitHub repo and
on GetBootstrap. A working version of the walker for Bootstrap 4 can be found in the v4 branch.
Acording to @mdo & team:
Long story short, shipping a beta means were done breaking all your stuff until our next major version
(v5).
Installation
Place wp-bootstrap-navwalker.php in your WordPress theme folder /wp-content/your-theme/
Open your WordPress themes functions.php file /wp-content/your-theme/functions.php and add the
following code:
// Register Custom Navigation Walker
require_once get_template_directory() . 'wp-bootstrap-navwalker.php';
If you encounter errors with the above code use a check like this to return clean errors to help diagnose
the problem.
if ( ! file_exists( get_template_directory() . 'wp-bootstrap-navwalker.php' ) ) {
// file does not exist... return an error.
return new WP_Error( 'wp-bootstrap-navwalker-missing', __( 'It appears the wp-bootstrap-
navwalker.php file may be missing.', 'wp-bootstrap-navwalker' ) );
} else {
// file exists... require it.
require_once get_template_directory . 'wp-bootstrap-navwalker.php';
}
Usage
Update your wp_nav_menu() function in header.php to use the new walker by adding a "walker" item to
the wp_nav_menu array.
<?php
wp_nav_menu( array(
'menu' => '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())
);
?>
Your menu will now be formatted with the correct syntax and classes to implement Bootstrap dropdown
navigation.
You will also want to declare your new menu in your functions.php file.
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'THEMENAME' ),
) );
Typically the menu is wrapped with additional markup, here is an example of a navbar-fixed-top menu
that collapse for responsive navigation.
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-
navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo home_url(); ?>">
<?php bloginfo('name'); ?>
</a>
</div>

<?php
wp_nav_menu( array(
'menu' => '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())
);
?>
</div>
</nav>
To change your menu style add Bootstrap nav class names to the menu_class declaration.
Review options in the Bootstrap docs for more information on nav classes.
Displaying the Menu
To display the menu you must associate your menu with your theme location. You can do this by selecting
your theme location in the Theme Locations list wile editing a menu in the WordPress menu manager.
Making this Walker the Default Walker for Nav Manus
There has been some interest in making this walker the default walker for all menus. That could result in
some unexpected situations but it can be achieved by adding this function to your functions.php file.
function prefix_modify_nav_menu_args( $args ) {
return array_merge( $args, array(
'walker' => WP_Bootstrap_Navwalker(),
) );
}
add_filter( 'wp_nav_menu_args', 'prefix_modify_nav_menu_args' );
Simply updating the walker may not be enough to get menus working right, you may need to add
wrappers or additional classes, you can do that via the above function as well.
Extras
This script included the ability to add Bootstrap dividers, dropdown headers, glyphicons and disables
links to your menus through the WordPress menu UI.
Dividers
Simply add a Link menu item with a URL of # and a Link Text or Title Attribute of divider (case-
insensitive so divider or Divider will both work ) and the class will do the rest.
Glyphicons
To add an Icon to your link simple place the Glyphicon class name in the links Title Attribute field and
the class will do the rest. IE glyphicon-bullhorn
Dropdown Headers
Adding a dropdown header is very similar, add a new link with a URL of # and a Title
Attribute of dropdown-header (it matches the Bootstrap CSS class so it's easy to remember). set
the Navigation Label to your header text and the class will do the rest.
Disabled Links
To set a disabled link simply set the Title Attribute to disabled and the class will do the rest.

VERZIJA @

A custom WordPress nav walker class to fully implement the Bootstrap 3.0+ navigation style in
a custom theme using the WordPress built in menu manager.

NOTES
This is a utility class that is intended to format your WordPress theme menu with the correct
syntax and classes to utilize the Bootstrap dropdown navigation, and does not include the
required Bootstrap JS files. You will have to include them manually.
Bootstrap 4
Bootstrap 4 beta is available and is now the default branch offered at the GitHub repo and
on GetBootstrap. A working version of the walker for Bootstrap 4 can be found in the v4 branch.
Acording to @mdo & team:
Long story short, shipping a beta means were done breaking all your stuff until our next major
version (v5).

Installation
Place wp-bootstrap-navwalker.php in your WordPress theme folder /wp-content/your-
theme/
Open your WordPress themes functions.php file /wp-content/your-
theme/functions.php and add the following code:
// Register Custom Navigation Walker
require_once get_template_directory() . 'wp-bootstrap-navwalker.php';
If you encounter errors with the above code use a check like this to return clean errors to help
diagnose the problem.
if ( ! file_exists( get_template_directory() . 'wp-bootstrap-navwalker.php' )
) {
// file does not exist... return an error.
return new WP_Error( 'wp-bootstrap-navwalker-missing', __( 'It appears
the wp-bootstrap-navwalker.php file may be missing.', 'wp-bootstrap-
navwalker' ) );
} else {
// file exists... require it.
require_once get_template_directory . 'wp-bootstrap-navwalker.php';
}

Usage
Update your wp_nav_menu() function in header.php to use the new walker by adding a
"walker" item to the wp_nav_menu array.
<?php
wp_nav_menu( array(
'menu' => '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())
);
?>
Your menu will now be formatted with the correct syntax and classes to implement Bootstrap
dropdown navigation.
You will also want to declare your new menu in your functions.php file.
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'THEMENAME' ),
) );
Typically the menu is wrapped with additional markup, here is an example of a navbar-fixed-
top menu that collapse for responsive navigation.
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo home_url(); ?>">
<?php bloginfo('name'); ?>
</a>
</div>

<?php
wp_nav_menu( array(
'menu' => '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())
);
?>
</div>
</nav>
To change your menu style add Bootstrap nav class names to the menu_class declaration.
Review options in the Bootstrap docs for more information on nav classes.
Displaying the Menu
To display the menu you must associate your menu with your theme location. You can do this by
selecting your theme location in the Theme Locations list wile editing a menu in the WordPress
menu manager.
Making this Walker the Default Walker for Nav Manus
There has been some interest in making this walker the default walker for all menus. That could
result in some unexpected situations but it can be achieved by adding this function to your
functions.php file.
function prefix_modify_nav_menu_args( $args ) {
return array_merge( $args, array(
'walker' => WP_Bootstrap_Navwalker(),
) );
}
add_filter( 'wp_nav_menu_args', 'prefix_modify_nav_menu_args' );
Simply updating the walker may not be enough to get menus working right, you may need to
add wrappers or additional classes, you can do that via the above function as well.
Extras
This script included the ability to add Bootstrap dividers, dropdown headers, glyphicons and
disables links to your menus through the WordPress menu UI.
Dividers
Simply add a Link menu item with a URL of # and a Link Text or Title
Attribute of divider (case-insensitive so divider or Divider will both work ) and the class will
do the rest.
Glyphicons
To add an Icon to your link simple place the Glyphicon class name in the links Title
Attribute field and the class will do the rest. IE glyphicon-bullhorn
Dropdown Headers
Adding a dropdown header is very similar, add a new link with a URL of # and a Title
Attribute of dropdown-header (it matches the Bootstrap CSS class so it's easy to remember).
set the Navigation Label to your header text and the class will do the rest.
Disabled Links
To set a disabled link simply set the Title Attribute to disabled and the class will do the rest.

Sa sajta http://kaloraat.com/articles/WordPress-theme-
development-from-scratch-part-1-theme-template-header-
and-footer
Deo1
WordPress Theme Development From Scratch Part 1 : Theme
Template, Header and Footer
Category: WordPress Updated 11 months ago by Ryan Dhungel

So you want to learn WordPress theme development from scratch, Great! Surely, You know how to use WordPress. you have also used free and

premium WordPress themes. It is great to simply search and download themes. With little effort, you can set up your websiteand go live. But you

don't always get lucky to find the perfect theme you are looking for, right?

You also want complete control of your website. You want to understand how everything is working behind the scene so that you customize the

design, manipulate certain functions and optimize your site for better performance.

If you are working for a client, most likely you need to customize the theme to get the desired header, footer, navigation and page layout with

extra elements etc.

If you are reading this article, that means you understand what it means to learn WordPress theme development. You have clearly seen the potential

of learning this awesome skill. The possibilities are endless.

What will you learn?

I am going to make these tutorials incredibly well explained and make 100% practical. Just so that you don't get stuck in the middle, I will also make

the source code available in github for you to download for each part as we progress. You are not far away from creating your dream theme that

works exactly the way you want.By the end of these tutorial series you will gain full understanding of:

Convert HTML Template to WordPress Theme


Template Breakdown to Header, Footer, Sidebar etc

Create Bootstrap Dropdown Navigation System

Loop Through Posts, Post Meta, Excerpt etc

Featured Image, Sidebar Widgets etc

Post Formats, Templates and Gallery

Custom Front Page and Icon Boxes

Use Font Awesome Icons

Create and Implement Theme Customizer API

List of WordPress theme development from scratch tutorials series

WordPress theme development from scratch Part 1 : Theme template, header and footer

WordPress theme development from scratch Part 2 : Create a bootstrap dropdown menu using wp-bootstrap-navwalker

WordPress theme development from scratch Part 3 : Post loop, post meta, excerpt and featured image

WordPress theme development from scratch Part 4 : Single post, page and comments

WordPress theme development from scratch Part 5 : Sidebar widgets, archive page

WordPress theme development from scratch Part 6 : Post formats, templates and gallery

WordPress theme development from scratch Part 7 : Custom full width front page, icon boxes, font awesome and widgets

WordPress Theme Development from Scratch Part 8 : Create Fields for Theme Customizer API

WordPress Theme Development from Scratch Part 9 : Implement Theme Customizer API and Pagination

Requirements

Basic knowledge of HTML CSS and Bootstrap

Comfortable with basics of PHP

Comfortable with WordPress admin panel

local development enviroment such as MAMP, AMPPS or XAMPP installed and ready to use

While you can work on live host, It is way better to create your own local development enviroment (localhost) using MAMP, XAMPPetc so that you

can install WordPress locally. WPbeginner have a good article about it.

Goals

Be able to use bootstrap for layout

Set up a brand new WordPress theme

Convert html template to WordPress theme

Template breakdown to header, footer, page layout etc

Dynamically load meta tags, stylesheets, header and footer

Understand how WordPress header and footer works and the elements inside it

Getting Strarted
Before we start working with WordPress, we want to have a html page template ready. We will convert the html template to WordPress theme along

the way.

Using Bootstrap web framework

We will be using twitter bootstrap for the layout. It is the most popular web framework for front end development. It is a css and javascriptframework

that is fully responsive and mobile ready. It makes your life as a web developer a lot easier. In fact it is the most popular framework out there which

is very easy to start with, if you have basic commands of html and css. If you don't know much about it, don't worry. You will learn along the way.

Here are some of the reasons for using bootstrap:

It is fully responsive so that you dont have to worry about your site not rendering properly in mobile devices

It is the most popular web framework and most loved by web developers across the world

It is easy to learn, even if you have never used bootstrap you will be able to catch up along the way
Creating a template

You can create your own website template or use an existing one. In this tutorial We will create a front page template for our theme which you can

see above. I will also be using bootstrap's blog template from it's official website which you can see below. It will look different than blog page.

To make it easy for you to follow along I have these templates with html, css and javascript saved in github. The folder is called wpbootstrap, It includes

bootstrap css and bootstrap javascript file as well as font-awesome css so you don't need to dowload bootstrap or font-awesome seperately.

So download it from github. If you dont have an account with github then you can create one for free. It's easy. Once you download it, unzip and place it

on your desktop for ease of use.

Now if you open frontpage.html and index.html in your browser, you can see index.html which is our blog posts page and also frontpage.html which is

our front page. You can see how they look on the browser. That is what we will be building. Lets start converting it to a theme.

Convert html to WordPress theme


Now we have html template with css ready to convert to a WordPress theme. The first thing we need here is a fresh install of WordPress. I am sure

you have a local enviroment setup for theme development right?

Through out these series I will be using MAMP, you could be using XAMPP, AMPPS, WAMP etc. Go ahead and download latest version of

WordPress and extract it in your htdocs or www folder. Give it any name you like, I am calling it wpbootstrap. Now start MAMP and click on Open

WebStart page. From there, click on phpMyAdmin, click on Databases, create a database in phpmyadmin with the name you like. I am calling it

wpbootstrap. Now open up your favourite web browser, go to http://localhost/ (or http://localhost:8000/ ).

Click on the name you gave to your WordPress install earlier and follow up the installation. Make sure you type the correct database name. I am

putting root as my username and password both. Click submit and run the installation for the fresh copy of WordPress. Fill out the information on

welcome page and click on install WordPress. You will be prompted with the success window. Now click login and fillout login form with the username

and password you created earlier on welcome page. Great, You are in the admin dashboard of your local WordPress install.

Now go to MAMP/htdocs/wpbootstrap/wp-content/themes . There you will find bunch of themes that comes with WordPress by default. You will also find

index.php. Leave them as they are, We will be creating our own custom theme from scratch.

Create a theme folder

Create a folder called wpbootstrap in wp-contents/themes. wpbootstrap is the name of our new theme. There must be at least two files in

any theme for WordPress to recognize it as a theme. So let's go ahead and create two files, they are index.php and style.css. I will be

using sublime as my favourite text editor.

Theme declaration

We will start off with style.css. You can put your theme related info as shown below. You must have at least Theme Name for your themeto work. The

other informations are not mandatory however you should put some information about your theme. You don't want to just write down your theme name

and leave right?

Feel free to modify the information below to suit your theme. To read more about it and other valuable information about WordPress theme

development, you can always go to official WordPress site . Remember to keep this information always on top of your stylesheet.

/*
Theme Name: wpbootstrap
Theme URI: http://kaloraat.com
Author: Ryan Dhungel
Author URI: http://kaloraat.com/
Description: WordPress theme built with bootstrap
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: bootstrap
Text Domain: wpbootstrap
This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/

Discover your theme from WordPress admin panel

Now if you go to your WordPress admin Appearance/themes, you will see your theme there. Cool right? However your theme does not have

any image like the other themes do. Let's add an image. Find an image you like with the width of 1200px and height of 900px or above. Name your

image screenshot.png and place inside your theme folder together with index.php and style.css.

Go back to the browser and refresh the page, you will see your theme with an image. Great! Now you can activate your theme and visitthe front

page. What do you see? It's all white right? That's because we don't have anything in our index.php yet. Lets start working on the content.

Bring the html, css files to the theme directory

It is time to bring the files that you downloaded earlier from github which contains index.html, bootstrap css and js etc.

CSS/JavaScript

First copy the js folder and paste it in your theme folder.

Create a new folder in your theme folder and name it css.

Go to your download folder and copy the bootstrap.css file and paste it inside your theme's css folder.

Open up the blog.css from your downloads folder, copy all the css.

In your theme folder, open style.css and paste the css that you copied from blog.css. Paste it right below the theme declaration that we

made earlier.

HTML

Open up index.html from your downloads folder and copy all the html code.

In your theme folder, open index.php and paste the html code that we copied.

Now if you refresh the page, you will see that we now have index page with all the content we downloaded earlier. However it is missing styling

because it is missing the stylesheet. Let's load stylesheet dynamically.

PHP functions in WordPress

Now that we are going to turn our static html page to dynamic WordPress theme, we will be using PHP. We all know that WordPress is built on PHP.

If you are familier with the basics of php, you will be love it. If you don't know anything about php you might get a little confused but take it easy. Take it

slow and don't get overwhelmed.

There are bunch of php functions that are WordPress specific. You will get used to it along the way. Remember we don't have to write any php code

on our own. Most of it will be WordPress specific and we will use them at the right time at the right place.

Just keep in mind that php is written with the opening <?php and closing ?> tag.
Load stylesheet

Now our first step is to load stylesheet dynamically using a function instead of hard-coding it. This is our first step towards getting dynamic.

Go to index.php and Select the code below:

<link href="/css/blog.css" rel="stylesheet">

Replace with the following code:

<link href="<?php bloginfo('stylesheet_url'); ?>" rel="stylesheet">

We will be updating some of our functions so that our theme meets the current standard but for the moment, Let's stick with the easiest

options available.

See how we inserted php function inside html link to load the stylesheet dynamically? This is how we will be doing things from now on. The

WordPress way!

Let's do the same with bootstrap stylesheet too. But with this we will be using template instead of stylesheet. That way WordPress will go looking for

the location of the current template.

<link href="<?php bloginfo('template_url'); ?>/css/bootstrap.css" rel="stylesheet">

Now if you go back to the browser and reload the page, you will see that our page have got the styles back.

Start adding dynamic content

Now that we have set up our stylesheets correctly, the next thing we will do is replace the static index page with dynamic content. We will start

working form the head section.

Load language attribute

Load the language attribute dynamically so that we can change it using admin panel. Currently we have specified en like this in our head section:

<html lang="en">
Let's make it dynamic

<html <?php language_attributes(); ?>>

Meta tags

This is what our meta tags in head section look like at the moment

<meta charset="utf-8">
<meta name="description" content="">

Let's make them dynamic now with the code below:

<meta charset="<?php bloginfo('charset' ); ?>">


<meta name="description" content="<?php bloginfo('description') ?>">

Now you can go to the reload the front page and see the source code. You can see the language attributes, charset and description are all there

that is generated dynamically.

Title

Currently we have static title text, Let's make that dynamic with our site name.

<title><?php bloginfo('name'); ?> | <?php wp_title(); ?></title>

Now we have dynamically generated the page title. You can go to admin panel Settings/general and change the site title.

It is great but the front page will have no description such as sample-page or blog post title etc after the site title, thats why we have to use php termery

operator to display site description dynamically.

<title><?php bloginfo('name'); ?> |


<?php is_front_page() ? bloginfo('description') : wp_title(); ?>
<?php wp_title(); ?></title>

Now the front page will have the title and description seperated by '|' pipe symbol while the other pages will have page or post name and the main title

accordingly.
Header

Now there is one more important thing to do with head section. put this line of code right before the closing </head> tag.

<?php wp_head(); ?>

This is really important because when we use third party plugins or widgets that needs to interact with the head section, This function will be

necessary. Now if you go to your page and see the source code, you will see a bunch of script generated in the head section.

You will also see the white space above the menu created as soon as you put that function, This space will be used for admin bar for logged in users.

Footer

Let's add a dynamic footer as well right after the closing </footer> tag.

<?php wp_footer(); ?>

Go and reload the page, you will see the top bar populated with admin options. Also if you check the source code, bunch of script is loaded in footer.

Seperate the header and footer files

Our next step is to seperate header and footer from the index page and include then using the php function. Go to index.php and copy the code from

the top to closing mastehead div in the body that includes navbar.

Here is the full code to copy:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come
*after* these tags -->
<meta name="description" content="<?php bloginfo('description'); ?>">

<title><?php bloginfo('name'); ?> | <?


php is_front_page() ? bloginfo('description') : wp_title(); ?><?php wp_title(); ?></title>

<!-- Custom styles for this template -->


<link href="<?php bloginfo('template_url'); ?>/css/bootstrap.css" rel="stylesheet">
<link href="<?php bloginfo('stylesheet_url'); ?>" rel="stylesheet">
<link href="/css/font-awesome.css" rel="stylesheet">
<?php wp_head(); ?>
</head>

<body>

<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item active" href="#">Home</a>
<a class="blog-nav-item" href="#">New features</a>
<a class="blog-nav-item" href="#">Press</a>
<a class="blog-nav-item" href="#">New hires</a>
<a class="blog-nav-item" href="#">About</a>
</nav>
</div>
</div>

Create header.php

In your theme folder, create a file called header.php and paste the above code and save. Now go back to index.php and delete the copied text and paste

this function instead

<?php get_header(); ?>

It will load header.php file.

Create footer.php

Go and do the same with footer. Copy from the begining of footer tag to all the way down to the end of page.

Here is the full code to copy:

<footer class="blog-footer">
<p>Blog template built for <a href="http://getbootstrap.com">Bootstrap</a> by
<a href="https://twitter.com/mdo">@mdo</a>.</p>
<p>
<a href="#">Back to top</a>
</p>
</footer>
<?php wp_footer(); ?>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js "></script>


<script src="/js/bootstrap.min.js"></script>
</body>
</html>

Create a file called footer.php and paste the code that you copied and save. Now go back to index page and delete the copied code and put this

function instead which will load footer.php file.

<?php get_footer(); ?>

Now you can reload the page and see that everything is working perfectly however we did seperate header and footer from our index page and placed

them on their own pages. Now we can include them on any page we want using get_header or get_footer function. We will be taking things off the index

page one by one such as blog posts etc and load them dynamically.

Dynamic copyright text with date

Now we are going to put dynamic copyright text with date and name in footer. Go to footer.php and find the code below:

Blog template built for Bootstrap by @kaloraat.

We will echo the current year followed by the site name in footer with the code below:

<p>&copy; <?php echo Date('Y'); ?> - <?php bloginfo('name'); ?></p>

Dynamic website header and description

Go to index.php and copy this as well so that we can dynamically change the website header and description instead of static content. Paste the

following code in the bottom of the header.php then go back and delete from the index page because it is already included in header.php
<div class="container">
<div class="blog-header">
<h1 class="blog-title">The Bootstrap Blog</h1>
<p class="lead blog-description">The official example template of creating a blog with
Bootstrap.</p>
</div>

As you can see the title and description is static. Let's make it dynamic so that we can change it from the wp admin. Replace the above code with the

code below:

<div class="container">
<div class="blog-header">
<h1 class="blog-title"><?php bloginfo('name'); ?></h1>
<p class="lead blog-description"><?php bloginfo('description') ?></p>
</div>

Now you can log into the wp dashboard, go to setting - general and change the information dynamically.

Conclusion

Let's wrap up this first part here. So far we learned how we can load things dynamically in WordPress and control from the admin panel. We also

learned about header and footer which is very important part of the whole development process because most of the time we need

to customize header and footer while working in any website project either for yourself or a client.

We have made ourself familer with header and footer. We also understand how WordPress has its own php functions to do certain tasks such as

loading stylesheet, template, header and footer. We will learn more about functions in coming series.

In Part 2, We will learn to Create a bootstrap dropdown menu using wp-bootstrap-navwalker .

This is just the begining, There will be a lot of exciting things happening in future lessions. Keep practicing and I will come up with the next part shortly. I

hope you all had fun learning and developing your WordPress skill. Leave your comments below.

For any development related questions, feel free to use our forum.

Deo 2
WordPress Theme Development From Scratch Part 2 : Create a
Bootstrap Dropdown Menu Using wp-bootstrap-navwalker
Category: WordPress Updated 11 months ago by Ryan Dhungel
In this Wordpress theme development from scratch series part 2, We will be creating a bootstrap dropdown menu using wp bootstrap

navwalker. To be able to use bootstrap specific navigation system in WordPress we need to download a class called wp-bootstrap-navwalker from

github. Before we dive right into it, Let's recap what we learned in the Part 1.

We learned how to start creating a theme with just index page and a stylesheet. Then we started to break down the template and make things load

dynamically and control from the WordPress admin. We did seperate header and footer from the main template too. Now let's implement a

dynamic dropdown menu to our header section.

Requirement

Completed WordPress theme development from scratch Part 1 : Theme template, header and footer

You can also download the theme from github as it was completed in part 1, extract in your theme folder and start with this tutorial

Goals

Use bootstrap dropdown menu with WordPress

Create WordPress functions

Download and use php functions from github repository and use in your project

Be able to create / update menu from WordPress admin dashboard

Using wp-bootstrap-navwalker in WordPress

We will be using wp bootstrap navwalker function from github repository that will let us implement bootstrap dropdown navigation system in

our WordPress theme. The first thing we need to do is head over to github and download wp-bootstrap-navwalker.

Extract the zip file that you just download. There you will find wp-bootstrap-navwalker.php file. Copy that file and paste inside your theme folder. Your

directory structure should look something like this:

wp-contents/themes/wpbootstrap/wp-bootstrap-navwalker.php

Createing theme functions

It is time for us to create functions.php file inside our theme folder. We will be writting all the functions inside this file.

The first thing we need to do is require the wp-bootstrap-navwalker file. Make sure you have the opening <?php tag at the begining of the file.

See the code below:

<?php
// Register Custom Navigation Walker
require_once('wp_bootstrap_navwalker.php');
Now we are going create a function to add theme support for our bootstrap navigation. You will also notice that we are using double

underscore __ which is a WordPress function for localization that you can use to wrap your static text around.

// Add theme support to bootstrap navigation


function my_theme_setup()
{
register_nav_menus(array(
'primary' => __('Primary Menu')
));
}
add_action('after_setup_theme', 'my_theme_setup');

We have also added add_action function in order to make this theme_setup function work. What it does is hook into WordPress and tells WordPress

when and where to fire up this function. There are a lot of hooks available to use, you can read more on WordPress codex . For this instance we

used after_setup_theme, followed by our function name.

Using bootstrap navigation

Now let's head back to the wp-bootstrap-navwalker github page and copy the wp_nav_menu function. Feel free to read through the entire page to get a

better understanding.

Here is the code to copy:

<?php
wp_nav_menu( array(
'menu' => '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 go to header.php and replace all the blog-nav-item within nav tag such as <a class="blog-nav-item active" href="#">Home</a> with the code above.
Now if you reload your page, you will see a menu that says Add a menu. That is because we have not assigned any menu yet. You can click on Add a

menu or simply go to the admin Appearance/Menus and create a new menu. Give it a name and add some custom links if you want to and

choose Primary Menu from the Menu Settings and save.

Now if you go the front page and reload it again, you will see that you have your menu working. However we need to sytle our menu a bit, It is barely

visable.

Styling the navbar

We have made the bootstrap navigation working, which is great. Lets change the font color to white and also add white background color on hover.

We want to make it look good.

Add the following css to your style.css

.blog-nav a{
color: #fff;
}

.blog-nav li a:hover{
background-color: #fff;
color: #428bca;
}

Now our menu looks good. Let's see if we can use dropdown menu or not.

Go to WordPress admin and create some pages just for testing. Once you created few pages, go to Appearance/Menus, select those new pages and

click on add to menu. Now put them below any other menu title and slightly drag towards right and leave. Now they are within the parent page title.

Go and reload the front page to see your dropdown menu. Oopps! It's not working. But it is an easy fix.

Go to your footer.php and find the code below, which is pointing to bootstrap.js.

<script src="/js/bootstrap.min.js"></script>

That will no longer work. We need to let WordPress find it in the dynamically using the bloginfo template function instead. Use the code below instead.

<script src="<?php bloginfo('template_url'); ?>/js/bootstrap.js"></script>

Now you should have dropdown menu working great.


Conclusion

In this part, we successfully implemented a bootstrap navigation system to our theme. We also touched a bit on functions. We will learn more about

the functions in future tutorials. In the next part, we will learn how to loop through blog posts, post meta such as published date, author name etc,

excerpt and featured image . I hope you are making good progress. Don't forget to leave your comments below.

If you encountered any issues along the way, you can also use our forum to get help.

Deo 3
From Scratch Part 3 : Post Loop, Post Meta, Excerpt and Featured
Image
Category: WordPress Updated 11 months ago by Ryan Dhungel

In this Part of WordPress theme development from scratch series, We will learn how to dynamically loop through each blog

post use excerpt and also add featured image support to our theme. I hope you are following me from part 2. Currently we have all static content on

our pages. Lets create some sample blog posts from the WordPress admin panel and load them dynamically on our website.

Requirements

Completed WordPress theme development from scratch Part 1 : Theme template, header and footer

Completed WordPress theme development from scratch Part 2 : Create a bootstrap dropdown menu using wp-bootstrap-navwalker

You can also download the theme from github as it was completed in part 2, extract in your theme folder and start with this tutorial

Goals

Loop through each posts and display on the frontend

Use excerpt on blog posts

Dynamically load post meta content such as date and author name

Add featured image function to our theme

Getting Started

Lets start off by creating some sample blog posts. I will be creating 4 blog posts with some lorem epsum text that you can copy from this site . I will

also create some categories, tags and assign to each posts along the way.

Now if you go to the index.php, you can see that we have <div class="col-sm-8 blog-main"> which contains all the blog posts. Within that div there

is <div class="blog-post"> which contains each blog posts. As you can see, we have three blog posts there. Now instead of those static text blocks, we

want to show the posts that we just created from within the WordPress admin.

The first thing we need to do is delete the other two blog-post and keep only one.
Loop through each posts

Now let's check if there are any blog posts already created. Put this function right before the begining <div class="blog-post"> tag. While there are

posts, this function will loop through each of them.

<?php if(have_posts()) : ?>


<?php while(have_posts()) : the_post(); ?>

End this loop with the code below. Put it right after the ending </div> tag. If there are no posts then it will display the message posts not found!

<?php endwhile; ?>


<?php else : ?>
<?php __('Sorry, Posts not found!') ?>
<?php endif; ?>

Now if you save and reload the page. You will not see much difference except the same old static text repeted the same number of times as your blog

posts are. For example if you went ahead and created 3 sample blog posts with me earlier then you will see it repeted 3 times. Anyway let's start

displaying the actual posts.

Display post title and content

Let's start off with the title. Go to the index page and find this bit of code.

<h2 class="blog-post-title">Sample blog post</h2>

Replace with the code below:

<h2 class="blog-post-title"><?php the_title(); ?></h2>

Just a friendly note here, I hope you are writting all the code snippets that I have put here. Don't just copy and paste, type them alland you will get

much better understanding of what you are doing. It makes a big difference!

Now select all your static html content and delete except this line below. Leave it there, we will come back to work on it later.
<p class="blog-post-meta">January 1, 2014 by <a href="#">Mark</a></p>

We will load the post content dynamically. Use the code below to replace your static html content.

<?php the_content(); ?>

Now I don't know about you guys but I am super excited. Go ahead and reload the page. All the posts that you created earlier through WordPress

admin are there. Wow, This is cool stuff!

Use excerpt to display the post content

Our blog page looks good. But do we want the complete blog to show up on the blog lists page? Obviously not! We want to show only few lines as

excerpt and show a button that says read more or something similar right? Lets do that, It's easy!

Use the code below to replace <?php the_content(); ?>

<?php the_excerpt(); ?>

Now go back to the browser and reload the page. The excerpt function is working. It's amazing, isn't it?

Create a function to control the length of the excerpt

Our excerpt length at the moment is the default length defined by WordPress. Let's create a function that will lets us control the length. That way we

can make it either longer or shorter depending on our need. Using the code below we can limit our excerpt to 30 words. Open up function.php and

add the code below.

// Excerpt length
function set_excerpt_length()
{
return 30;
}
add_filter('excerpt_length', 'set_excerpt_length');

Here we added a filter called excerpt_length and supply our function name as the second parameter. Now go and reload the page to see all your blog

posts excerpts are displaying with only 30 words excerpt.


Add link to single post page

Now we have a list of blog posts with short excerpt as we wanted. But we can not click anywhere to get into the single post page and read the entire

post. That is not very convenient, is it? Let's add a link to the title so that we can click on the title to get to the single post page.

Head over to index.php and wrap your title <?php the_title(); ?> with the code below:

<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

Now reload the page. All you post's title is clickable. Once you click, you get to the single post page. Awesome!

Load Published date, Author name and Author posts

Date and time

Currently we have static date and author name displayed right below the title of our blog posts. Lets make them dynamic so that the post date and

author name is displayed dynamically. This is what we have at the moment:

<p class="blog-post-meta">January 1, 2014 by <a href="#">Mark</a></p>

You can delete the static date and replace with the following function:

<?php the_date(); ?>

Or you can also use the time function, Try the code below:

<?php the_time(); ?>

You can read more about the php date and time functions in the official php website to customize it further. I am using the code below which displays

the date as well as the time which is pretty cool.

<?php the_time('F j, Y g:i a'); ?>

Author name, Author posts


Now lets put life to the author name and also the link so that when we click on it, we get to the page where all the blog posts from that particular author

is available. Select this bit of code <a href="#">Mark</a> and replace with the code below:

<a href="<?php echo get_author_posts_url(get_the_author_meta('ID')) ?>"><?php the_author();


?></a>

Now the author name is generated dynamically. If you click on the author name, you will get to the page with all his posts. Now your url should have

such format yourtheme/author/yourname each time you click on the author name.

Add Featured Image support

Currently our theme does not support featured image. If you go to WordPress admin and click on to add a new post or go to an existing post, you will

notice that there is no place for featured image. Let's add featured image support to our theme.

Head over to functions.php and find the function below:

function my_theme_setup()
{
// Navigation
register_nav_menus(array(
'primary' => __('Primary Menu')
));
}

This is the same function that we created earlier. All we have to do is add add_theme_support('post-thumbnails'); to this function.

Here is what it should look like once you add the support for image:

function my_theme_setup()
{
// Add featured image
add_theme_support('post-thumbnails');
// Navigation
register_nav_menus(array(
'primary' => __('Primary Menu')
));
}
Now you can go to your old posts or create a new post and add featured image to it. It's all good but you can not see the image on the front page yet.

We need to do some work on our front page. Let's go for it.

Display featured image

Head over to index.php and find this line of code:

<?php the_excerpt(); ?>

We want to show the featured image right above the excerpt right? Put this line of code right above the excerpt. It will first look for the post image and

display if it has one.

<?php if(has_post_thumbnail()) : ?>


<?php the_post_thumbnail(); ?>
<?php endif; ?>

Now you can reload the page to see the images on each blog posts. But do they look too big? That's what I see. They are not fitting in. Let's wrap that

in a div so that it fits well inside. Let's wrap it up.

<div class="post-thumb">
<?php the_post_thumbnail(); ?>
</div>

Now go to your style.css and add the following code:

.post-thumb img{
width: 100%;
height: auto;
margin-bottom: 10px;
}

We added 100% width so that it takes all the width available within that div. We left the height to auto so that it don't get distorted and also added a bit

of margin to the bottom. Now reload your page to see the magic. Well not really magic but it's looking pretty good with all the images right?

Just in case you missed along the way, here is what we have so far within <div class="col-sm-8 blog-main"> </div> in our index.php
<div class="col-sm-8 blog-main">
<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
<div class="blog-post">
<h2 class="blog-post-title"><a href="<?php the_permalink(); ?>"><?
php the_title(); ?></a></h2>
<p class="blog-post-meta"><?php the_time('F j, Y g:i a'); ?> by <a href="<?
php echo get_author_posts_url(get_the_author_meta('ID')) ?>"><?phpthe_author(); ?></a></p>
<?php if(has_post_thumbnail()) : ?>
<div class="post-thumb">
<?php the_post_thumbnail(); ?>
</div>
<?php endif; ?>
<?php the_excerpt(); ?>
</div><!-- /.blog-post -->
<?php endwhile; ?>
<?php else : ?>
<?php __('Sorry, Posts not found!') ?>
<?php endif; ?>
<nav>
<ul class="pager">
<li><a href="#">Previous</a></li>
<li><a href="#">Next</a></li>
</ul>
</nav>

</div><!-- /.blog-main -->

and here is our function.php file so far

<?php
// Register Custom Navigation Walker
require_once('wp_bootstrap_navwalker.php');

// Add theme support to bootstrap navigation


function my_theme_setup()
{
// Add featured image
add_theme_support('post-thumbnails');
// Navigation
register_nav_menus(array(
'primary' => __('Primary Menu')
));
}
add_action('after_setup_theme', 'my_theme_setup');

// Excerpt length
function set_excerpt_length()
{
return 30;
}
add_filter('excerpt_length', 'set_excerpt_length');

Conclusion

This is all we are going to do in this part. Here we learned about looping through each posts and publishing them. We also looked at adding meta

content such as date, time and author name to the posts. And lastly we worked on adding theme support to featured image and displaying them.

We did a lot of cool stuffs.

In Part 4, We will learn about single post, single page and comments functions. Lots of cool stuffs ahead.

Stay in touch, Leave your comments below and use our forum for any difficulty you encounter along the way.

Deo 4

WordPress Theme Development From Scratch Part 4 : Single Post, Page and Comments
In this part of WordPress theme development from scratch series, We will be working on single post and
single page and comments. So far we learned how to create blog posts from within WordPress admin and
display in the front page by looping through each of them. That was cool but when we click on each blog
title we see a page that looks exactely like the index page because it is using index.php. But we want to
make single posts look different. That is what we will be doing in this part.

I hope you are following me from part 3. If you haven't gone through previous tutorials, I recommend you
to start from part 1. That way you will get full understanding of what we are doing here. It is always a
good idea to get comfortable with the basics, that way you can move ahead with confidence and ease.

Requirement

Completed WordPress theme development from scratch Part 1 : Theme template, header and footer
Completed WordPress theme development from scratch Part 2 : Create a bootstrap dropdown menu using
wp-bootstrap-navwalker
Completed WordPress theme development from scratch Part 3 : Post loop, post meta, excerpt and featured
image
You can also download the theme from github as it was completed in part 3, extract in your theme folder
and start with this tutorial

Goals

Create single post


Create single page
Enable comments functionality
Create single.php

The first thing we need to do is create a file called single.php. Go inside your theme folder and create
single.php. This will be used for blog post. Each time we click on the blog title or read more etc to see the
entire blog we will be taken to this page. Now if you reload the page, you will no longer see the blog post,
all you see is white screen. As soon as you create single.php, WordPress loads this page by default for
your blog post. WordPress is smart!

Let's copy all the code from our index.php and paste it into single.php. In Case you are a bit lost, Let me
show you what we have in our index.php by now.

This is the code we have in index.php at the moment

<?php get_header(); ?>

<div class="row">

<div class="col-sm-8 blog-main">


<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
<div class="blog-post">
<h2 class="blog-post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="blog-post-meta"><?php the_time('F j, Y g:i a'); ?> by <a href="<?php echo
get_author_posts_url(get_the_author_meta('ID')) ?>"><?php the_author(); ?></a></p>
<?php if(has_post_thumbnail()) : ?>
<div class="post-thumb">
<?php the_post_thumbnail(); ?>
</div>
<?php endif; ?>
<?php the_excerpt(); ?>
</div><!-- /.blog-post -->
<?php endwhile; ?>
<?php else : ?>
<?php __('Sorry, Posts not found!') ?>
<?php endif; ?>
<nav>
<ul class="pager">
<li><a href="#">Previous</a></li>
<li><a href="#">Next</a></li>
</ul>
</nav>

</div><!-- /.blog-main -->

<div class="col-sm-3 col-sm-offset-1 blog-sidebar">


<div class="sidebar-module sidebar-module-inset">
<h4>About</h4>
<p>Etiam porta <em>sem malesuada magna</em> mollis euismod. Cras mattis consectetur purus sit
amet fermentum. Aenean lacinia bibendum nulla sed consectetur.</p>
</div>
<div class="sidebar-module">
<h4>Archives</h4>
<ol class="list-unstyled">
<li><a href="#">March 2014</a></li>
<li><a href="#">February 2014</a></li>
<li><a href="#">January 2014</a></li>
<li><a href="#">December 2013</a></li>
<li><a href="#">November 2013</a></li>
<li><a href="#">October 2013</a></li>
<li><a href="#">September 2013</a></li>
<li><a href="#">August 2013</a></li>
<li><a href="#">July 2013</a></li>
<li><a href="#">June 2013</a></li>
<li><a href="#">May 2013</a></li>
<li><a href="#">April 2013</a></li>
</ol>
</div>
<div class="sidebar-module">
<h4>Elsewhere</h4>
<ol class="list-unstyled">
<li><a href="#">GitHub</a></li>
<li><a href="#">Twitter</a></li>
<li><a href="#">Facebook</a></li>
</ol>
</div>
</div><!-- /.blog-sidebar -->

</div><!-- /.row -->

</div><!-- /.container -->

<?php get_footer(); ?>

If you copy and paste the above code from index.php page to single.php and reload the page. you will see
that your blog post is back.

Remove the link from blog title

We still have the title link to our blog title. That is not necessary in single page, so let's remove that. Find
the code below.

<h2 class="blog-post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

Replace with the code below:

<h2 class="blog-post-title"><?php the_title(); ?></h2>

Dispaly full blog content

You must have noticed that our single post shows only excerpt, not the full content. Lets display the
content instead of excerpt.

Replace <?php the_excerpt(); ?> with the code below:

<?php the_content(); ?>

Now if you reload the page, you will see that the blog has the full content, not only excerpt.
We are doing things slow here so that it is completly understood and sink well into our brain so that we
can create WordPress themes like a pro in coming days. How does that sound?

Comments Functionality

What do you think about having a comments section right below the blog post? Cool right? That's what
everyone's doing. People come to read your blog and leave their comments. And it is as easy as it sounds.
You will love it.

Put the code below right under <?php the_content(); ?> This will enable the comments function to our
theme. It's really easy.

<?php comments_template(); ?>

If you reload the page, you can see the comments functionality is working great.

Create comments.php

Comments function is working good however you might want more control over it's appearance and
functionality. For that we need to create a new file called comments.php

Go to your theme folder and create a folder called comments.php

In comments.php, create a div and give it a class name called comments so that we can style it later. Also
create a heading and call it Comments. See the code below:

<div class="comments">
<h2>Comments</h2>
</div>

Comments function and Comments Form

Below we are calling two functions wp-list-comments and comment-form function. First we are calling
wp-list-comments followed by the arguments array for the comment form. Then we are calling for
comment-form function followed by the arrays of arguments that let us change the title of the send button,
change the title of the reply section etc

Copy the code below and paste it right after the <h2>Comments</h2>. I copied the code for the wp-list-
comments function from WordPress functions reference page and also copied the code for comment-form
from this WordPress functions reference page.

<?php $args = array(


'walker' => null,
'max_depth' => '',
'style' => 'ul',
'callback' => null,
'end-callback' => null,
'type' => 'all',
'reply_text' => 'Reply',
'page' => '',
'per_page' => '',
'avatar_size' => 32,
'reverse_top_level' => null,
'reverse_children' => '',
'format' => 'html5', // or 'xhtml' if no 'HTML5' theme support
'short_ping' => false, // @since 3.6
'echo' => true // boolean, default is true
);
?>
<?php wp_list_comments( $args, $comments );

$comments_args = array(
// change the title of send button
'label_submit'=>'Post',
// change the title of the reply section
'title_reply'=>'Write a Reply or Comment',
// remove "Text or HTML to be displayed after the set of comment fields"
'comment_notes_after' => '',
// redefine your own textarea (the comment body)
'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment',
'noun' ) . '</label><br /><textarea id="comment" name="comment" aria-
required="true"></textarea></p>',
);

comment_form($comments_args);
?>

Now save it and reload the page. That looks similar right? You can change the heading, button text etc in
comments.php. The only thing left to do is style it. Since we have already wrapped it in a div with a class
name comments Let's go ahead and do some styling.

Styling the comment section

So far we have successfully implemented comments functionality to our theme. We also put functions in
comments.php and got a better understanding of how the whole thing works. Let's add some styling to it
so that it looks good too.

Feel free to copy and modify the css below. Put it in style.css.

/* comments section */

.comments{
border: 1px solid #ccc;
padding: 10px;
}

.comments h3, .comments h2{


color: #333;
padding: 5px;
}

.comment-body{
border: 1px solid #ccc;
padding: 20px 10px;
}
#comment-2{
list-style-type: none;
background: #fff;
}

.comments-meta img{
float: left;
}

.comment-reply-link{
background: #f4f4f4;
color: #666;
display: inline-block;
padding: 10px 15px;
}

.comment-form input{
padding: 5px 20px;
border: 1px solid #428bca;
background: #428bca;
color: #fff;
}

.comment-form input:hover{
background: #fff;
color: #428bca;
}

.comment-form textarea{
width: 100%;
height: 200px;
}

Ok, Now we have single post page with comments working great. Let's move on to the single page

Create page.php

It is time for us to create page.php inside our theme folder. Go ahead and create page.php and save.
Reload the page and go to one of the pages you created earlier. All you see is white right? For the moment
let's copy all the code from single.php and paste inside page.php. Reload the page to see the same layout
as the others.

Since this template will be used for pages, we want to make it look different. We will do further
customization later with full width image background and call to action buttons etc but for the moment
let's make some small changes to it so that the page is identical.

Let's remove the meta content, comments and featured image from the single.php. This is all the code we
have left in page.php now.

<?php get_header(); ?>

<div class="row">
<div class="col-sm-8 blog-main">
<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
<div class="blog-post">
<h2 class="blog-post-title"><?php the_title(); ?></h2>
<?php the_content(); ?>
</div><!-- /.blog-post -->
<?php endwhile; ?>
<?php else : ?>
<?php __('Sorry, Page not found!') ?>
<?php endif; ?>
<nav>
<ul class="pager">
<li><a href="#">Previous</a></li>
<li><a href="#">Next</a></li>
</ul>
</nav>

</div><!-- /.blog-main -->

<div class="col-sm-3 col-sm-offset-1 blog-sidebar">


<div class="sidebar-module sidebar-module-inset">
<h4>About</h4>
<p>Etiam porta <em>sem malesuada magna</em> mollis euismod. Cras mattis consectetur purus sit
amet fermentum. Aenean lacinia bibendum nulla sed consectetur.</p>
</div>
<div class="sidebar-module">
<h4>Archives</h4>
<ol class="list-unstyled">
<li><a href="#">March 2014</a></li>
<li><a href="#">February 2014</a></li>
<li><a href="#">January 2014</a></li>
<li><a href="#">December 2013</a></li>
<li><a href="#">November 2013</a></li>
<li><a href="#">October 2013</a></li>
<li><a href="#">September 2013</a></li>
<li><a href="#">August 2013</a></li>
<li><a href="#">July 2013</a></li>
<li><a href="#">June 2013</a></li>
<li><a href="#">May 2013</a></li>
<li><a href="#">April 2013</a></li>
</ol>
</div>
<div class="sidebar-module">
<h4>Elsewhere</h4>
<ol class="list-unstyled">
<li><a href="#">GitHub</a></li>
<li><a href="#">Twitter</a></li>
<li><a href="#">Facebook</a></li>
</ol>
</div>
</div><!-- /.blog-sidebar -->

</div><!-- /.row -->

</div><!-- /.container -->


<?php get_footer(); ?>

Now you can reload the page and see that we have removed the meta content with the date and author
info from the page and also the featured image is gone.

In the next chapter, we will be adding widgets to the sidbar.

Conclusion

In this tutorial, we understood how WordPress works with single post and pages. We not only learned to
create and implement single post and page but also learned how to enable comments system too. By now
you must be feeling comfortable to work with WordPress. The more we know the more we get
comfortable working with it and become an awesome developer.

In the next part, We will be working with widgets that will eventually replace the static text sidebar that
we currently have. I hope you are working along with me. Learning the basics is the most important thing,
if you know the basics well then you will be able to move on your own and create something amazing in
future.

So keep up the good work and leave your comments below. For any development related issues, you can
use our forum.

Deo 5

WordPress Theme Development From Scratch Part 5 : Sidebar


Widgets, Archive Page
Category: WordPress Updated 11 months ago by Ryan Dhungel
In this part of WordPress theme development from scratch series, we will learn how to implement sidebar widgets functionality to our theme and

also create archive page. Currently we have static html text in our sidebar. We don't want that right? Let's start working on widgets, It will be fun.

Requirements

Completed WordPress theme development from scratch Part 1 : Theme template, header and footer

Completed WordPress theme development from scratch Part 2 : Create a bootstrap dropdown menu using wp-bootstrap-navwalker

Completed WordPress theme development from scratch Part 3 : Post loop, post meta, excerpt and featured image

Completed WordPress theme development from scratch Part 4 : Single post, page and comments

You can also download the theme from github as it was completed in part 4, extract in your theme folder and start with this tutorial

Goals

Implement widgets support to our theme

Create sidebar widgets

Create archive page

One quick not here is that you can use widgets anywhere on the page right, left, top or bottom. You are not limited to use it on sidebar. It is just named

sidebar!

Create widgets function

If you go to WordPress admin and look into Appearance, you will not see the widgets. That is because we have not put the widget's function into

our functions.php yet. Let's do that.

Open up functions.php and add the code below:

// Widgets
function my_init_widgets($id)
{
register_sidebar(array(
'name' => 'Sidebar',
'id' => 'sidebar',
'before_widget' => '<div class="sidebar-module">',
'after_widget' => '</div>',
'before_title' => '<h4>',
'after_title' => '</h4>'
));
}
add_action('widgets_init', 'my_init_widgets');
Here we created a function and named it my_init_widgets then supplied an array of information. We have specified the name, before

widget and after widget div and title h4 etc. Remember the div class with sidbar-module <div class="sidebar-module"> in our page sidebar where all

the static sidebar text is sitting at the moment? We will populate that ares with the widgets instead.

Then we hook it with WordPress using add_action. There we supplied the hook name and the name of our function as a second parameter. You can

read more about hooks in WordPress codex .

You can go ahead and reload the page to see the widgets option available in Appearance. Go ahead click on the widgets, drag and dropcategories

to the sidebar. Give it a title and save. Now if you reload the page, you will see no change because we still have that static html text on the sidebar.

Delete the static html content from the sidebar

Go to your index.php and delete everything we have inside the blog sidebar. Your div must be empty now.

See the code below:

<div class="col-sm-3 col-sm-offset-1 blog-sidebar">

</div><!-- /.blog-sidebar -->

Display sidebar widgets

index.php

First thing we need is to determine if we have any sidebar widgets at all. Put the code below inside the the div that we just made empty. The code

speaks for itself right? It first checks if there is active sidebar, then displays dynamically.

<?php if(is_active_sidebar('sidebar')): ?>


<?php dynamic_sidebar('sidebar'); ?>
<?php endif; ?>

Go ahead, save your index.php and reload your site. Do see you categories in sidebar? Of course you do because you created categories earlier

while creating posts right? If not go ahead and create some categories and assign them to your posts. Let's further customizeour sidebar

by dragging more items to it. I am adding archive and calendar.

Make sure you also add archive on the sidebar. We will be creating archive.php soon.

Move the widgets to sidebar


Widgets working great but we don't want to repeat this code to all other pages such as single.php and page.php. So the better solution here is

to move them to sidebar.php instead. Let's do that.

Create sidebar.php

Create a file called sidebar.php and put inside your theme folder. Then go to index.php and copy the div that contains blog sidebar and paste it

in sidebar.php. Here is the code to copy and paste into sidebar.php.

<div class="col-sm-3 col-sm-offset-1 blog-sidebar">


<?php if(is_active_sidebar('sidebar')): ?>
<?php dynamic_sidebar('sidebar'); ?>
<?php endif; ?>
</div><!-- /.blog-sidebar -->

Now go back to index.php and replace the div that contains blog sidebar with the code below:

<?php get_sidebar(); ?>

Now reload the page to see the sidebar widget working as expected. You can include sidebar in each page you like using the code above. We will

include it in single.php and page.php.

single.php and page.php

Now that we have sidebar.php that contains widgets. Let's use it on single.php and page.php. Delete the entire sidebar from those pages and replace

with the code below.

<?php get_sidebar(); ?>

That's it. It is easy to work with sidebar widgets in WordPress.

Reload you page and click on the blog posts, categories or archives. You can see the sidebar is working great.

Create archive.php
If you click on the link of archives, you will see the page layout similar to others. However you can customize it the way you like. Let's go ahead and

create archive.php and save it in our theme folder. Now if you reload one of your archive page you will see nothing. Lets copy all the code

from index.php and paste into archive.php to begin with. Now if you reload the page, It looks similar to any other page.

We can do a lot with it, feel free to play around and customize further. You can remove the sidebar <?php get_sidebar(); ?> or make the main

blog div full width by changing the bootstrap div class from col-md-8 to col-md-12 etc. Just play around with it.

The idea here is to understand how all these pages work in WordPress. We now know how archive.php works, it works in a similar fashion as

the index.php or single.php.

Conclusion

When we first start to learn WordPress theme development, we see all these pages such as sidebar, archives, single, comments, functions etc

that makes us confused. You don't know where to begin. But if you have been following me from the part 1 you now understand how all these pages

are coming to work together. I am sure you feel much comfortable with WordPress by now. Which is exactely what we want.

We are making really good progress here. In the next part we will work on custom post format which is one of the
most powerful featureof WordPress. This is it for this part, leave your comments below and feel free to use
our forum for any questions you have.

Deo 6

WordPress Theme Development From Scratch Part 6 : Post Formats,


Templates and Gallery
Category: WordPress Updated 11 months ago by Ryan Dhungel

In this part 6 of WordPress theme development from scratch series, we will learn about Post Formats, Templates and Gallery. Post format is used by

WordPress themes to customize its presentation of a post. In this part, we will learn how to implement post formats functionality to our theme. There

are numbers of post formats available such as aside, gallery, link, image, quote, status, video, audio and chat. You can read more about post format

in codex at WordPress. In this tutorial we will use aside and gallery. Once you understand how it works, you can add more to it.

Also in this tutorial, we will learn how to use Templates so that we do not need to repeat our code over and over again. Let's start off with template first.
Requirement

Completed WordPress theme development from scratch Part 1 : Theme template, header and footer

Completed WordPress theme development from scratch Part 2 : Create a bootstrap dropdown menu using wp-bootstrap-navwalker

Completed WordPress theme development from scratch Part 3 : Post loop, post meta, excerpt and featured image

Completed WordPress theme development from scratch Part 4 : Single post, page and comments

Completed WordPress theme development from scratch Part 5 : Sidebar widgets, archive page

You can also download the theme from github as it was completed in part 5, extract in your theme folder and start with this tutorial

Goals

Use content template

Create different post formats

Getting Started

So far we did a lot of work and created bunch of files. We have also repeated ourself multiple time writting the same code such as <?php the_title(); ?

>, <?php the_author(); ?> , <?php the_content(); ?> in different files such as index, single, archive, page etc. It is not a good practice to repeat code like

this. We can use templates instead and load them on each page as required.

Create content.php

Let's go ahead and create content.php inside our themes folder. The first thing we want to do is go to index.php and copy the code that is

sitting inside while loop. Go ahead and copy everything within <?php while(have_posts()) : the_post(); ?> and <?php endif; ?>. This is where the post

title, date, author, featured image and comments are.

The code you need to copy is below:

<div class="blog-post">
<h2 class="blog-post-title"><?php the_title(); ?></h2>
<p class="blog-post-meta"><?php the_time('F j, Y g:i a'); ?> by
<a href="<?php echo get_author_posts_url(get_the_author_meta('ID')) ?>"><?
phpthe_author(); ?></a></p>
<?php if(has_post_thumbnail()) : ?>
<div class="post-thumb">
<?php the_post_thumbnail(); ?>
</div>
<?php endif; ?>
<?php the_content(); ?>
<?php comments_template(); ?>
</div><!-- /.blog-post -->

Now go to content.php and paste the code that you copied and save the file. Now we can delete the above code from index.php and use get template

part function instead.

See the code below:

<?php get_template_part('content'); ?>

What we did here is just cut the code from index.php, put into content.php and use the function get template part to load it. Pretty simple. Have you also

noticed that our index.php is looking pretty neat now. That's what we want right?

Load content in single.php

Now let's go ahead and do the same thing in single.php. Delete everything within <?php while(have_posts()) : the_post(); ?> and <?php endif; ?> and

put the code below instead.

<?php get_template_part('content'); ?>

Remove the title link from single page

Now if you go to one of your post page, you will notice that the title link is again clickable. We don't want it to be clickable in single page. Let's go

to content.php and put an if condition. Find <h2 class="blog-post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> and replace

with the code below:

<h2 class="blog-post-title">
<?php if(is_single()) : ?>
<?php the_title(); ?>
<?php else : ?>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
<?php endif; ?>
</h2>
All we did here is check if it is single page or not. if single page then we want only title else we want the title with permalink. Now if you reload the

page, you will your single post title has no link. Awesome!

Display the full content if it is single page

Now we are loading the contents from content.php into index.php and single.php. We need to make sure that the entire blog post is displayed if it is

a single page but only excerpt is displayed if it is an index page. Lets fix this. In our content.php you will find <?php the_excerpt(); ?> right before the

ending div tag. Let's put a conditional if statement to it. We will also enable comments template if it is single page.

See the code below:

<?php if(is_single()) : ?>


<?php the_content(); ?>
<?php else : ?>
<?php the_excerpt(); ?>
<?php endif; ?>

<?php if(is_single()) : ?>


<?php comments_template(); ?>
<?php endif; ?>

Do you like what you are doing? If you are not used to all this stuff, It will take you some time to get used to but trust me, we are doing good and we

are cleaning up our code and loading things the WordPress way! Go back and reload the page. Now we have single pagewith full content and also with

comments. Let's move on and do the same thing with archive.php

Load content in archive.php

Now we can go ahead and do the same thing in archive .php. Delete everything within <?php while(have_posts()) : the_post(); ?> and <?php endif; ?

> and put the code below instead.

<?php get_template_part('content'); ?>

This one is easy!

Post Format - Aside


Our theme currently does not support post format. The first thing we need to do is add theme support for post formats. Open up your functions.php and

put this code inside my_theme_setup() function. Make sure you put inside the functions closing {}

// Post format
add_theme_support('post-formats', array('aside', 'gallery'));

Now go to WordPress admin to create a sample post. You will notice that now we have a post format options available.

Create content-aside.php

Create a sample post and assign it a post format of aside. Now if you reload the front page you can see the new post but it looks no different than other

posts. To change that, first we need to create a content-aside.php file in our theme folder.

Also in your index.php, find this line of code:

<?php get_template_part('content'); ?>

Now add get_post_format as a second parameter. Replace the above code with the code below:

<?php get_template_part('content', get_post_format()); ?>

Also make the same change to archive.php and single.php.

Please don't reload the page to see any changes because you won't see any. We still got more to do. Head over to content-aside.php, copy the code

from below and paste in there. Or you can type yourself, That's better. The more you code the better you become.

<div class="blog-post post-aside">


<div class="well">
<small><?php the_author(); ?>@<?php the_date(); ?></small>
<?php the_content(); ?>
</div>
</div>

I am sure you know what's going on here. We put author name, date and the content in a div with the class of well, which is a bootstrap class that puts

gery background with padding.

Now you can reload the page and see the change. Yes! Our post with the format option of aside stands out form the rest. It is formatted differently than

the others. This is great! You now know what you can do with post formats. You can get as creative as you want, go for it!

Post Format - Gallery

Are you excited? I am excited because working with images are always fun. Let's go to WordPress admin and create a post with gallery. Click on add

media, create gallery and choose the best images for your gallery. Click on insert gallery, give it a post format of galleryand click publish.

Create content-gallery.php

I know you are excited to reload the page to see your beautiful gallery but there is one more file to create. Create a file called content-gallery.php inside

your theme folder and paste the following code:

<div class="blog-post post-gallery">


<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>

Now reload the page and smile. I am smilling, looking at those beautiful images. I hope you also had beautiful images. Shall we add some styling to it?
Styling the gallery

I gave the heading a similar blue color to match the navbar. I also used dark background for the images, added some padding and center the text etc.

/* gallery */
.post-gallery h2{
color: #428bca;
}

.post-gallery{
background: #333;
padding: 10px;
color: #fff;
text-align: center;
}

Please replace <?php get_template_part('content'); ?> with <?php get_template_part('content', get_post_format()); ?> in single.phpand archive.php too.

Conclusion

We are pretty much done with the blog. In the next part will start working on custom front page. I know you have been waiting for that. That is coming

up next. Thank you all for learning with me. I am sure you are loving the WordPress theme development. It is fun and at the same time a valuable

skill to have. Learning to know how WordPress works as a system and being able to go along with it and creating something amazing in near future is

within your reach.

Deo7
WordPress Theme Development From Scratch Part 7 : Custom Full
Width Front Page, Icon Boxes, Font Awesome and Widgets
Category: WordPress Updated 11 months ago by Ryan Dhungel

In this WordPress theme development from scratch Part 7, we will create Custom Front Page, Icon Boxes with Font Awesome Icons and

Widgets. In the last part we learned how to load things from template and simplify our code. Most importantly, we learned how to use post

formats and also used few of them. That was fun and this part will be even more fun.

Requirements

Completed WordPress theme development from scratch Part 1 : Theme template, header and footer

Completed WordPress theme development from scratch Part 2 : Create a bootstrap dropdown menu using wp-bootstrap-navwalker

Completed WordPress theme development from scratch Part 3 : Post loop, post meta, excerpt and featured image

Completed WordPress theme development from scratch Part 4 : Single post, page and comments

Completed WordPress theme development from scratch Part 5 : Sidebar widgets, archive page

Completed WordPress theme development from scratch Part 6 : Post formats, templates and gallery

You can also download the theme from github as it was completed in part 6, extract in your theme folder and start with this tutorial

Goals

Create custom front page

Use full width layout

Use font awesome icons

Use the icon boxes as widgets

Getting Started

The first we need to do is get inside the WordPress admin and create two pages with the title of Home and Blog, leave them completly blank and

click publish. We will make Home a front page which is also going to be a landing page. Then the Blog page will feature all the latest blog posts we

create.

Once you have published those pages, go to Settings/Reading and choose Home as your front page and Blog as your posts page and then save.

Now go to Appearance/Menus and add those pages to your menu and save.

Now if you reload your page you will see that our home page is empty whereas blog page has all the blogs. Great. Let's start working on the front

page.

Create front-page.php
Our front page must have a different layout then the rest of the pages. So the first thing we need to do here is create a file called front-page.php in

our theme folder and save. Now if you reload the home page, all you see is a white screen because we just created it, we haven't done anything yet.

However, WordPress is smart enough to detect front-page.php and loads it automatically.

Do you remember the startup template you downloaded from github when we started WordPress theme development in part 1? You still have that,

haven't you? I give you a link here anyway in case you need to download it from github again. There you will find frontpage.html. We will make similar

front page for our theme.

Open up frontpage.html and keep it aside. The reason we are keeping it aside is because we can't copy paste the whole code. Since we have our

own header and footer files etc

Loading header and footer

Open up front-page.php and call for get header and get footer function.

<?php get_header() ?>

<?php get_footer(); ?>

Now we have header with navigation and footer working in the front page.

Bringing the front page content

Now we need to copy the content from frontpage.html which you downloaded from github and Paste it right between get header and get footer

function in our front-page.php.

Make sure you do not copy the header, navigation and footer sections because we just included them using get header and get footer.

Just in case you are a bit confused, I am posting the complete code for front-page.php. It looks a lot but don't worry. It is all static text!

See the code below:

<?php get_header() ?>


<section>
<div class="jumbotron text-center">
<h1>wp_bootstrap theme development</h1>
<p>Learn to develop responsive WordPress themes from scratch with kaloraat.com</p>
<a class="btn btn-primary btn-lg" href="http://kaloraat.com">Read more</a>
</div>
</section>
<article>
<div class="boxes">
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="box">
<i class="fa fa-coffee" aria-hidden="true"></i>
<h3>Lorem epsum dolor</h3>
<p>Eiusmod fugiat velit ita nisi, officia ipsum noster vidisse
quorum, proident o
quorum, quibusdam lorem fugiat do noster. Voluptate minim id
senserit
comprehenderit. Nostrud a noster proident ad ut legam
expetendis comprehenderit.
Duis hic an aute litteris, aliquip quorum lorem ab summis. Et
duis si nulla ea
noster ex litteris.</p>
</div>
</div>
<div class="col-md-4">
<div class="box">
<i class="fa fa-gears" aria-hidden="true"></i>
<h3>Lorem epsum dolor</h3>
<p>Eiusmod fugiat velit ita nisi, officia ipsum noster vidisse
quorum, proident o
quorum, quibusdam lorem fugiat do noster. Voluptate minim id
senserit
comprehenderit. Nostrud a noster proident ad ut legam
expetendis comprehenderit.
Duis hic an aute litteris, aliquip quorum lorem ab summis. Et
duis si nulla ea
noster ex litteris.</p>
</div>
</div>
<div class="col-md-4">
<div class="box">
<i class="fa fa-bolt" aria-hidden="true"></i>
<h3>Lorem epsum dolor</h3>
<p>Eiusmod fugiat velit ita nisi, officia ipsum noster vidisse
quorum, proident o
quorum, quibusdam lorem fugiat do noster. Voluptate minim id
senserit
comprehenderit. Nostrud a noster proident ad ut legam
expetendis comprehenderit.
Duis hic an aute litteris, aliquip quorum lorem ab summis. Et
duis si nulla ea
noster ex litteris.</p>
</div>
</div>
</div>
</div>
</div>
</article>
<?php get_footer(); ?>

Now you can reload the page to see your progress. You will notice two things.

Front page is not full width

It is missing the main image and displays only Read more button

We can not see font-awesome icons anymore

Making the front page fullwidth

Our front page is not full width at the moment. That is because our theme is using <div class="container"> to wrap all the contents inside of it. If you

head over to header.php, to the bottom of it, right after the nav you will see a div with a class of container at the end. We need to change this to container-

fluid. It is a bootstrap class that makes the container full width.

See the code below:

<div class="container-fluid">

Once you do that, reload the page. You front page is full width now. Awsome! But, if you go to blog page, that also has become full width. That's not

what we want right? Let's fix that up, It's easy!

Making the blog page not full width

We have to put a conditional if statement in our header.php to see if it is front-page or not. If it is a front page then we want it to use

the class name container-fluid to make it full width, if not then we want to use the class name container. In your header.php replace <div

class="container-fluid"> with the code below:

<?php if(is_front_page()) : ?>


<div class="container-fluid">
<?php else : ?>
<div class="container">
<?php endif; ?>

Now go ahead and reload the page. Our blog page is using the container class and our home page is using container-fluid class. Moving forward, you

can use such conditional statements anywhere in your theme to suit your need.
Change the background color of the container

Currently we can see only Read more button because the text is white and so is the background color. We will be using theme customizerto upload

image as the background later. But for the moment, Let's change the background color to something else than white so that we can see the text. Go

to style.css and find this:

.jumbotron{
height: 400px;
padding: 100px 20px;
color: #fff;
border-bottom: #ccc 1px solid;
margin-bottom: 30px;
color: #fff;
background: url(../images/clouds.jpg) no-repeat center center;
}

Let's add a background color before the url, see the code below and make adjustment.

background: #333 url(../images/clouds.jpg) no-repeat center center;

Now you can reload the page and see the heading that we had originally. We will be using theme customizer to control this heading too which will be

cool. But let's start off with the title, descriptions and icons.

Remove the blog title and the description from the front-page

You must have noticed that we have blog title and description on top of all the pages. We want them only on blog page, not on the front page. Let's

create another if statement to deal with that. Go to header.php and find this code which is at the bottom.

<div class="blog-header">
<h1 class="blog-title"><?php bloginfo('name'); ?></h1>
<p class="lead blog-description"><?php bloginfo('description') ?></p>
</div>

Replace the above code with the code below:

<?php if(!is_front_page()) : ?>


<div class="blog-header">
<h1 class="blog-title"><?php bloginfo('name'); ?></h1>
<p class="lead blog-description"><?php bloginfo('description') ?></p>
</div>
<?php endif; ?>

Here all we did is put the whole div in if condition. if it's ! front page then display the div. Cool right?

Bringing back the font-awesome icons

In the part 1 we used the WordPress templating system to load our stylesheets but we did not include font-awesome.css. Let's fix that up. First thing you

should have font-awesome.css inside your css folder. If you don't have that yet, Go ahead and find the folder that you downloaded from github earlier.

You will find font-awesome.css file there sitting inside css folder. Just copy and paste inside your thmes cssfolder.

Go to header.php and replace <link href="css/font-awesome.css" rel="stylesheet"> with the code below:

<link href="<?php bloginfo('template_url'); ?>/css/font-awesome.css" rel="stylesheet">

You can head over to font awesome official get started page and enter your email address to get your font-awesome embed code.

Or, simply use the code below. It will load font-awesome icons from bootstrap CDN. I love it!

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-


awesome.min.css">

Use icon box as widget

Our front page is looking great. The next step is to use those icon boxes as widgets so that we can control them from the widgets area from within

the WordPress admin.

Head over to functions.php and go to my_init_widgets function. There we already have register_sidebar widget array. We need to add 3 more widgets

and name each of them Box1, Box2 and Box3. We will basically copy the register_sidebar array and make changes to name,id, div class and

the heading.

Here is the full code for my_init_widgets function:

// Widgets
function my_init_widgets($id)
{
register_sidebar(array(
'name' => 'Sidebar',
'id' => 'sidebar',
'before_widget' => '<div class="sidebar-module">',
'after_widget' => '</div>',
'before_title' => '<h4>',
'after_title' => '</h4>'
));

register_sidebar(array(
'name' => 'Box1',
'id' => 'box1',
'before_widget' => '<div class="box">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>'
));

register_sidebar(array(
'name' => 'Box2',
'id' => 'box2',
'before_widget' => '<div class="box">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>'
));

register_sidebar(array(
'name' => 'Box3',
'id' => 'box3',
'before_widget' => '<div class="box">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>'
));
}
add_action('widgets_init', 'my_init_widgets');

Here we defined each div class name box, because that is the name we are using in our front-page.php where all the icons are wrapped within <div

class="box"></div>
Now if you go to WordPress admin Appearance/Widgets, you will see the new widgets that we created with the name of Box1, Box2 and Box3.

This is getting interesting right?

It is time to create widgets from within the WordPress admin and populate them dynamically to the icon boxes in the front page. First let's go to front-

page.php and copy the everything within <div class="col-md-4"> for each of the boxes, we have total three box. Below is the content that I am going to

copy from the first box.

<div class="box">
<i class="fa fa-coffee" aria-hidden="true"></i>
<h3>Lorem epsum dolor</h3>
<p>Eiusmod fugiat velit ita nisi, officia ipsum noster vidisse quorum, proident o
quorum, quibusdam lorem fugiat do noster. Voluptate minim id senserit
comprehenderit. Nostrud a noster proident ad ut legam expetendis comprehenderit.
Duis hic an aute litteris, aliquip quorum lorem ab summis. Et duis si nulla ea
noster ex litteris.</p>

</div>

Now go to WordPress admin Appearance/Widgets and drag a text widget from the left to Box1. Paste all the content that you copied earlier from the

first box and paste in there and click save. Do the same for other two boxes.

Now that we have already copied the content from each boxes, we can delete them and place the following code instead. It will load widgets that we

created from within WordPress.

Box1 - Widget
<?php if(is_active_sidebar('box1')) : ?>
<?php dynamic_sidebar('box1'); ?>
<?php endif; ?>

Box2 - Widget

<?php if(is_active_sidebar('box2')) : ?>


<?php dynamic_sidebar('box2'); ?>
<?php endif; ?>

Box3 - Widget

<?php if(is_active_sidebar('box3')) : ?>


<?php dynamic_sidebar('box3'); ?>
<?php endif; ?>

Now the icon box in the front page is using widgets. We can go to widgets and change the content, icons etc and display on the front page

dynamically. Cool stuff!

Conclusion

I think we did a really cool job in this part creating our front page. We learned to create a custom page and make it full width. We will further style it

later. We also used font awesome icons which was really easy to use and also great for presentation. We used widgets to control the icon boxes in

the front page which is the highlight of this part I guess. So far you must be feeling pretty good that you followed me all the way to this part. Now you

know a lot about WordPress. Follow along with me to become a superb WordPress developer in a very short time.

In the next part we will work further to implement theme customizer to control the front page layout such as the full width background

image, title and description.


WordPress Theme Development from Scratch Part 8 : Create Fields
for Theme Customizer API
Category: WordPress Updated 11 months ago by Ryan Dhungel

In this part of WordPress Theme Development from Scratch series, We are going to learn how to Create Fields for Theme Customizer

API and Implement them. This is an interesting feature of WordPress and this is what makes WordPress easy to use and customize for everyday

people who don't want to get their hands dirty with coding and stuff.

We have already learned how to add Widgets functionality to the icon boxes in the part 7. If you haven't tried using it from the frontend, go

to WordPress Dashboard Appearance/ Customize. There we have various theme customize options such as Site Identity, Menus, Widgets

Section etc. We want to be able to Add a field there to control the Showcase Image for our front page and also the Heading, Description

Text, Button text that sits in the middle and also the button link.

If you are jumping straight to this part, Just want to let you know that the front page Icon Boxes are the Widgets. We learned how to Create and

Implement Widgets on part 7.

Requirements

Completed WordPress theme development from scratch Part 1 : Theme template, header and footer

Completed WordPress theme development from scratch Part 2 : Create a bootstrap dropdown menu using wp-bootstrap-navwalker

Completed WordPress theme development from scratch Part 3 : Post loop, post meta, excerpt and featured image

Completed WordPress theme development from scratch Part 4 : Single post, page and comments

Completed WordPress theme development from scratch Part 5 : Sidebar widgets, archive page

Completed WordPress theme development from scratch Part 6 : Post formats, templates and gallery

Completed WordPress theme development from scratch Part 7 : Custom full width front page, icon boxes, font awesome and widgets
You can also download the theme from github as it was completed in part 7, extract in your theme folder and start with this tutorial

Goals

Create Option Fields for Theme Customizer API

Create customizer.php

We will start off by creating a new folder called inc inside our theme folder. Then we will create a new file called customizer.php and save it inside that

folder. Your folder directory should look like this:

wpbootstrap/inc/customizer.php

Now go to your functions.php and require that file, put it at the end.

// Theme Customizer
require get_template_directory(). '/inc/customizer.php';

Create customizer functions

Let's open up customizer.php and start writting functions. Here we are going to use customize_register function which is one of the many WordPress

hooks available. Once you are comfortable working with the function below, I encourage you to explore more about wordpress hooks by

visiting wordpress codex. First, Let me give you an introduction on what we are writting.

We will create a function my_customize_register and pass an object $wp_customize. Then we take that object and add_section to

that by providing an array of options.

The array of options includes title with the text that you want to display and the name of our theme. For the description we

use sprintf function and display the options info followed by the theme name with the priority of 130. Read more

about add_action and priority in wordpress developers page.

Then we add_setting for heading and pass an array with the default input value of WP Bootstrap Theme, which will be visable in

the customizer and also the options type of theme mode.

Now we also need to add_control with the heading and pass an array with label, section and priority.

Here is the code:

<?php
function my_customize_register($wp_customize)
{
// Showcase section
$wp_customize->add_section('showcase', array(
'title' => __('Showcase', 'wpbootstrap'),
'description' => sprintf(__('Options for showcase',
'wpbootstrap')),
'priority' => 130
));
$wp_customize->add_setting('showcase_heading', array(
'default' => _x('WP Bootstrap Theme', 'wpbootstrap'),
'type' => 'theme_mod'
));
$wp_customize->add_control('showcase_heading', array(
'label' => __('Heading', 'wpbootstrap'),
'section' => 'showcase',
'priority' => 2
));
}
add_action('customize_register', 'my_customize_register');

Remember my prefix we used in our functions.php ? we are just following that convention here. This function above speaks for itself. I suggest you to not

copy but write it down to get a better understanding.

Once you have written it all, save it and go to the theme customizer to see if it made any difference. Go to Appearance/Customize.

The Showcase option is right at the end. Now if you click on Showcase you will see that there is an Options for showcase and Heading with the

default name.

See the screenshot below:


Now if you try to make any change to the heading text, you will notice the screen flashes. That means the showcase heading is coming to effect.

Let's go ahead and do the same with the showcase text. We will basically copy the above code and modify a bit. Here is the code that you need to add

to the above function.

$wp_customize->add_setting('showcase_text', array(
'default' => _x('This WordPress theme is created from scratch
and using bootstrap.', 'wpbootstrap'),
'type' => 'theme_mod'
));
$wp_customize->add_control('showcase_text', array(
'label' => __('Text', 'wpbootstrap'),
'section' => 'showcase',
'priority' => 3
));

Now we have Text option available together with the heading. The next thing we want is a link option for the button and the text as well. Let's go

through the similar process twice.

Here is the code you need to add to your function:


$wp_customize->add_setting('btn_url', array(
'default' => _x('http://kaloraat.com', 'wpbootstrap'),
'type' => 'theme_mod'
));
$wp_customize->add_control('btn_url', array(
'label' => __('Button URL', 'wpbootstrap'),
'section' => 'showcase',
'priority' => 4
));
$wp_customize->add_setting('btn_text', array(
'default' => _x('Learn More', 'wpbootstrap'),
'type' => 'theme_mod'
));
$wp_customize->add_control('btn_text', array(
'label' => __('Button Text', 'wpbootstrap'),
'section' => 'showcase',
'priority' => 5
));

Now if you reload the customize page, you should see Heading, Text, Button URL and Button Text options like the screenshot above.. Let's add an

option for Image too.


$wp_customize->add_setting('showcase_image', array(
'default' =>
get_bloginfo('template_directory').'/img/showcase.jpg',
'type' => 'theme_mod'
));
$wp_customize->add_control(new WP_Customize_Image_Control($wp_customize,
'showcase_image', array(
'label' => __('Showcase Image', 'wpbootstrap'),
'section' => 'showcase',
'settings' => 'showcase_image',
'priority' => 1
)));

Okay Okay, I know It's a lot of code floating around. Here is the complete code from customizer.php.

<?php
function my_customize_register($wp_customize)
{
// Showcase section
$wp_customize->add_section('showcase', array(
'title' => __('Showcase', 'wpbootstrap'),
'description' => sprintf(__('Options for showcase',
'wpbootstrap')),
'priority' => 130
));
$wp_customize->add_setting('showcase_image', array(
'default' =>
get_bloginfo('template_directory').'/img/showcase.jpg',
'type' => 'theme_mod'
));
$wp_customize->add_control(new WP_Customize_Image_Control($wp_customize,
'showcase_image', array(
'label' => __('Showcase Image', 'wpbootstrap'),
'section' => 'showcase',
'settings' => 'showcase_image',
'priority' => 1
)));
$wp_customize->add_setting('showcase_heading', array(
'default' => _x('WP Bootstrap Theme', 'wpbootstrap'),
'type' => 'theme_mod'
));
$wp_customize->add_control('showcase_heading', array(
'label' => __('Heading', 'wpbootstrap'),
'section' => 'showcase',
'priority' => 1
));
$wp_customize->add_setting('showcase_text', array(
'default' => _x('This WordPress theme is created from scratch
and using bootstrap.', 'wpbootstrap'),
'type' => 'theme_mod'
));
$wp_customize->add_control('showcase_text', array(
'label' => __('Text', 'wpbootstrap'),
'section' => 'showcase',
'priority' => 2
));
$wp_customize->add_setting('btn_url', array(
'default' => _x('http://kaloraat.com', 'wpbootstrap'),
'type' => 'theme_mod'
));
$wp_customize->add_control('btn_url', array(
'label' => __('Button URL', 'wpbootstrap'),
'section' => 'showcase',
'priority' => 3
));
$wp_customize->add_setting('btn_text', array(
'default' => _x('Learn More', 'wpbootstrap'),
'type' => 'theme_mod'
));
$wp_customize->add_control('btn_text', array(
'label' => __('Button Text', 'wpbootstrap'),
'section' => 'showcase',
'priority' => 4
));

}
add_action('customize_register', 'my_customize_register');

Create an Image Directory

Now that's it for the functions for now. Head over to your theme directory and create a folder called img. Find a beautiful wide image and name that

showcase.jpg, it's the default image that we specified in the function above. Your image directory should look like this:

wpbootstrap/img/showcase.jpg

Now if you reload the customize page, you will see the default image and all other options we created so far.

Look at the screenshot below:

Conclusion
This is amazing, Isn't it? Until now you were probably wondering how those options lets us customize things in WordPress but now you know how all

that works. I mean it is begining to look clear to you right? We learned how to create functions for Theme Customizer in this part, In the next part we

will learn to Implement it.

I hope you are making a good progress with me on this WordPress theme development series. Please leave your comments below and use

our forum for questions and answers.

WordPress Theme Development from Scratch Part 9 : Implement


Theme Customizer API and Pagination
Category: WordPress Updated 11 months ago by Ryan Dhungel

In this part of WordPress Theme Development from Scratch series, We are going to Implement Theme Customizer API options that we created in

part 8. We will also implement Pagination. We want to be able to change the Showcase background image on the front page, change the Heading

Title, Description Text and also the Call to Action Button text and the link for that. In part 8, we started working on it and finished off writting functions

into our customizer.php file and then included into the functions.php.

Requirement

Completed WordPress theme development from scratch Part 1 : Theme template, header and footer

Completed WordPress theme development from scratch Part 2 : Create a bootstrap dropdown menu using wp-bootstrap-navwalker

Completed WordPress theme development from scratch Part 3 : Post loop, post meta, excerpt and featured image

Completed WordPress theme development from scratch Part 4 : Single post, page and comments

Completed WordPress theme development from scratch Part 5 : Sidebar widgets, archive page

Completed WordPress theme development from scratch Part 6 : Post formats, templates and gallery
Completed WordPress theme development from scratch Part 7 : Custom full width front page, icon boxes, font awesome and widgets

Completed WordPress Theme Development from Scratch Part 8 : Create Fields for Theme Customizer API

You can also download the theme from github as it was completed in part 8, extract in your theme folder and start with this tutorial

Goals

Implement Theme Customizer

Create Pagination

Implement showcase heading title option

We will start off by making the heading title work. Head over to front-page.php. There you will see the static heading wrapped in <h1> at the moment.

<h1>wp_bootstrap theme development</h1>

We need to replace that witht the code below:

<h1><?php echo get_theme_mod('showcase_heading', 'YAY I build a theme'); ?></h1>

Remember the showcase_heading that we created earlier in our customizer.php and used the type theme_mod? That is what we echo here and also

supplied 'wp_theme development'as a second parameter. This text will display in the front end by default. Now save and reload your customize page. You

can Change the heading from the customizer now. Replace the default text with whatever you like. You can see it changing live. Great!

Implement showcase description text option

Now we are going to do the same with showcase the description text. This is the static description text we have at the moment.

<p>Learn to develop responsive WordPress themes from scratch with kaloraat.com</p>

Let's replace that with the code below:

<p><?php echo get_theme_mod('showcase_text', 'Easiest tutorials ever


@ kaloraat.com'); ?></p>
Now the description text field is working too.

Implement showcase button link and text option

We are going to follow the same pattern here with the call to action button link and the button text. This is what we currently have.

<a class="btn btn-primary btn-lg" href="http://kaloraat.com">Read more</a>

Replace this static <a> href and text with the code below:

<a class="btn btn-primary btn-lg" href="<?


php echo get_theme_mod('btn_url'); ?>"><?php echo get_theme_mod('btn_text',
'Learn more'); ?></a>

If your theme customizer options are not working here then please repeat yourself from part 8 to get it right!

This is what we have acheived so far

Implement showcase background image option

Now the last thing to do with the theme customizer is to implement the background image option. This is the best part of the

whole customization process isn't it? We all love the ability to update the front image every now and then. Let's do that.

Currently we are using background color for the showcase box, which we have specified in our stylesheet. Head over to style.css and find the code

below and delete it:

background: #333 url(../images/clouds.jpg) no-repeat center center;

Now go to the header.php and and put this code right before the ending </head> tag.

<style>
.jumbotron{
background:
url(<?
php echo get_theme_mod('showcase_image', get_bloginfo('template_url').'/img/
showcase.jpg') ?>) no-repeat center center;
}
</style>

Here we have a default background called showcase.jpg, Please make sure you have an img folder with the image of that name available. If you

have been following me from the previous tutorial then I am sure you have that there.

Now You can go to your theme customizer and change, remove or update the background image as you like. Finally we have implemented

the theme customizer to our theme successfully.

Implement Pagination

Now that our theme is nearly done, there are a few things I would like to fix before I end this part. If you go to your blog posts, you will notice that we

have really nice buttons that says Previous and Next towards the end of our page. The sad thing about it is that it does not work. You might be

upset with me for coming to fix it at the end of all these tutorials series, In that case my appologies. It's an easy fix!

This is what we have in our index page, The static nav in the bottom.

<nav>
<ul class="pager">
<li><a href="#">Previous</a></li>
<li><a href="#">Next</a></li>
</ul>
</nav>

Let's bring these beautiful buttons to life using the code below:

<nav>
<ul class="pager">
<li><?php next_posts_link( 'Previous' ); ?></li>
<li><?php previous_posts_link( 'Next' ); ?></li>
</ul>
</nav>

Now if you reload the blog page and see them disappear, don't blame me. That is because WordPress defaults the blog posts shown on each page

to 10. Go to your WordPress dashboard Settings/Reading and change that to 1. Now its working!

Currently we are using this nav in mulitple pages. Instead of repeating this process on all of them we can use get template part function, go ahead and

create a file, name it bootom-nav.php and save it in your theme folder. Now you can paste the above code there and save.

Now on each page you want to include this nav, simply use the code below replacing the old static nav.

<?php get_template_part('bottom-nav'); ?>

Go ahead and make a change in index, page, archive and single. Awesome!

Once you get used to using WordPress functions, You will love working with WordPress. It's fun!

Making Showcase Image Full Width

Did you just shout out to me? Haha..

No I haven't forgot that. Actually I saved it to the end, It's easy fix and looks great. Just minus the jumbotron margin using the css below.

.jumbotron{
margin: 0 -20px;
}
Conclusion

We have successfully created a fully functioning WordPress theme from scratch. We wrote all the code and understand how each and every element

is working in the backend and the frontend. Not only that we have a blog, We have a complete website with custom front page with theme

customizer options too. This is a greate acheivment, absoletely amazing!

Thank you for being with me throught all these tutorials. I hope you learned a lot and will continue to sharpen up your skills further. This is just the

begining. I want you to be able to create much more professional themes in future.

You have learned the fundamentals of WordPress theme development here. I will come up with even more exciting and valuable tutorials in coming

days. Stay in touch. I encourage you to leave your comments and participate in our forum and help each others out.

I encourage you to start all these tutorials one more time so that you are fully comfortable working with wordpress and understand better. You have an

option of downloading the source code for each part from github as it was completed and start from there. I am sure it will be much fun this time!

You might also like