Adding Widgets
Adding a Sidebar
In order to add widgets, you must first register them in the functions.php code.
Add this directly after the after_theme_setup
action; this will be to set up widget locations. We’ll create a function, call it init_widgets()
and it will take an id
; then, we’ll say register_sidebar
. Now, even though this is called register_sidebar
, this is used with all widget positions, not just a sidebar. It takes in an array and it’s going to take a name
; this happens to be Sidebar
, but it could be anything. Then, we’ll also say before_widget
and after_widget
. Also, we’ll say before_title
and after_title
of the widget:
Because it’s a vestige from original wordpress code, any widget is known as a sidebar. Thus, when you register a widget, you register a sidebar. That does not mean the widget is a sidebar.
On our sample index.php page, we have added a sidebar in markup. The markup looks like this:
We are going to remove this and replace it with a widget sidebar. We’ve registered the sidebar widget (and other widgets) on functions.php. In the code above we have a div with the class of “block”. We do not want to move those to functions.php. We are going to add a class of “side-widget”. We change the code we added to functions.php to replace the ‘before widget’ through ‘after title’ empty ” with this, which actually contains what we want before the widget, after the widget, etc:
The sidebar markup on index.php will be replaced by this:
The sidebar will not show up yet. In order for any widgets to show up, we need to create them. Before we can create them, we need to initialize the widgets by adding the following to functions.php, after which widget management and creation will appear under appearance in the admin:
Now when we create a widget and add it to the sidebar, it will appear. We can add some additional styling to make it look better. Add this to styles.css:
We can add additional widgets. First we have to register each widget in functions.php, which will allow us to add content to the widgets via the admin, and then we need to add the widgets to the theme itself. To register the widget in functions.php, just copy-and-paste the code we used earlier (to register the sidebar) making whatever adjustments to name and before/after as needed. For example, this registers a showcase widget