How to add a Custom Widget to a Theme
One thing I love about WordPress is the ability to use Widgets. Widgets are designated places in a website template where users can add and arrange any content they want. Because the user doesn’t need to know any code, it is a very flexible way to have control over areas of a site. A widget could simply show a Search form now, but a few months later it could also contain a Newsletter Signup, a list of Recent Posts, and any number of other items.
Sometimes when using a theme, the widgets that are built-in are not the best fit for what is needed on the site. Fortunately, you can create your own WordPress widgets and add them to any theme very easily with just a few lines of code.
functions.php
First, we’ll need to setup a new widget. In your theme files, open functions.php and paste the following code at the bottom:
function add_my_widgets() { register_sidebar(array( 'name' => 'My New Widget', 'id' => 'my-new-widget', 'before_widget' => '<div class="widget">', 'after_widget' => '</div>' )); } add_action('widgets_init', 'add_my_widgets');
The function called “add_my_widgets” will set up a new widget. I called it “My New Widget” and gave it an ID of “my-new-widget” — now we can reference the widget’s ID later on. We declare the function and then use add_action to run it during the “widgets_init” hook (this is when WordPress loads all the widgets on page load).
page.php
Now that the widget is setup, let’s place it into the template. Open up page.php (or whatever template file) from your theme and find where you’d like the widget content to appear. Once you’ve found a good spot for your new widget, paste in the code:
<?php if (is_active_sidebar('my-new-widget')) : ?> <?php dynamic_sidebar('my-new-widget'); ?> <?php endif; ?>
This conditional code checks to see if the widget is registered and being used. If the widget is active, it will output all the contents here. This is important to do the check first, because if we say “output everything from the widget here” when the widget is not being used, WordPress will show an error message to the user.
Appearance > Widgets
Now that we’ve setup the new widget and placed it in our theme, all that’s left is to add content to it via the WP-admin backend. Go to Appearance > Widgets to see the new widget we’ve created. Add content to the widget and save it. Refresh the page that is using your modified template and you should see the content of the widget appear.
Leave a Reply