Have you ever wanted to use a WordPress’ widget somewhere other than your sidebar? WordPress has a template tag called
the_widget() which allows you to add a widget directly in your template files, wherever you’d like.
Insert Widget in Template File
First, locate the file where you want your widget to appear.
Second, you’ll need the PHP class name of the widget you want to use. Here’s a quick list of the default WordPress widget’s class names:
Looking to use Jetpack widgets instead? Check out our list of Jetpack widget class names. (coming soon)
Using the_widget() call
Your code will look something like this:
<?php the_widget( $widget, $instance, $args ); ?>
Let’s take a look at what each of those parameters do, and then some real-world examples.
Simply put, this is the class name of the widget you want to use (see list above). This is mandatory for
the_widget() call to work. For example, if you wanted to list out recent comments (with the default settings), you could just write this:
<?php the_widget( 'WP_Widget_Recent_Comments' ); ?>
Think of $instance as a way to customize the settings for each individual widget. These vary with each widget. Some WordPress widgets only contain a title, while others have 5 or 6 things you can customize.
Sticking with our recent comments example, let’s say you want to:
- rename the title from the default Recent Comments to Latest Discussion
- increase the number of comments to show from the default 5 to 10 (max of 15)
<?php the_widget( 'WP_Widget_Recent_Comments', 'title=Latest Discussion&number=10' ); ?>
When you register sidebars & widgetized areas, you can customize the HTML that appears before & after widget areas, as well as widget titles. You can do the same thing with each call of
the_widget() template tag.
Let’s say you wanted to change the output of the HTML surrounding your new Latest Discussions title. By default, it looks like this:
<h2 class="widgettitle">Latest Discussions</h2>
To make that an
<h3> instead, and remove the class, we’d simple do this:
<?php the_widget( 'WP_Widget_Recent_Comments', 'title=Latest Discussion&number=10', 'before_title=<h3>&after_title=</h3>' ); ?>
You can also add HTML code before & after the widget itself by using:
Real-world Application & Caveats
Many of the default WordPress widgets can be added to your template files using built-in functions & template tags instead. I recommend you go that route first. Those are more powerful, customizable and they were built for exactly that in mind.
You’ll likely find yourself using
the_widget() to insert custom widgets throughout your template. Jetpack adds a handful of useful widgets that you could use these examples with. Also, many plugins come with custom widgets that you might want to use outside of your sidebar.