Widgets are small blocks in WordPress that perform specific function like showing recent posts, post categories, navigation, search, etc. All WordPress theme comes with a number of premade widgets which you can see in Appearance > Widgets area.
WordPress Widgets cam be added very easily to your theme by following the given 2 steps:
To add a widget to a specific area, you have to first create a WordPress Sidebar in functions.php file.
Just add the below code to your theme functions.php file –
/*New Widget Area*/ function add_Widget_area() { register_sidebar(array( 'name' => 'New Widget Area', 'id' => 'new-Widget-Area', 'description' => 'Our new widget area', 'before_widget' => '<ul class="archives"><li>', 'after_widget' => '</li></ul>', 'before_title' => '<h2><a>', 'after_title' => '</a></h2>', )); } add_action( 'widgets_init', 'add_Widget_area' ); /*End/
Explanation – Here I have added a function add_new_sidebar whose work is to create a new sidebar. You can give any name to this function. This function in turn calls a WordPress inbuilt function register_sidebar which has the following arguments:
This will create a WordPress Sidebar. Now in the WordPress dashboard go to Appearance > Widgets, there you will see this new sidebar called New Widget Area on the right side of the page.
Open it by clicking the down arrow on its right side. Now drag and drop any available widget from the left side to inside this newly created sidebar. Finally click save button.
Here in the picture I am showing how to add search widget to our sidebar using WordPress drag and drop feature.
Now I have to call the sidebar in any WordPress Template of my choice like header.php, footer.php, index.php, page.php etc.
Below is the code, which you need to add to any template, where you want to show the sidebar:
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('new-Widget-Area') ) : endif; ?>
In this way I can create any number of WordPress Sidebars and use them with widgets to provide great functionality in my WordPress theme.
Share this article -