Add a WordPress Widget to a Theme

Add a WordPress Widget to a Theme

Posted by Rainey

Choosing a great WordPress theme is like a right of passage to beginning your relationship with WordPress.  There are some great ones and then there are the others.  But, after getting half of your content loaded you realize this theme has not been setup for widgets, or you need a new widget ready area. Fortunately, adding a widget area is not difficult as you might think.  To add a widget you will need to dive into some PHP, so let’s get our hands dirty.

1. Register the new widget in your themes function.php or widgets.php file by adding the PHP code below. This file will be in your theme folder, not in the main WordPress install. (There is a quicker way to do this, but this gives you more control)

register_sidebar(array(
'name' => 'Single Post Top',  //Choose a name, shows in admin
'id' => 'post_top', //A unique ID
'description' => 'Use this widget to include ads, widgets, etc. in the top of your posts.', //Descriptions shows in admin
'before_widget' => '<div class="post_top widgetBox">', //Set the element before your widget to match what your  theme's widget are using - also set any classes you may want for styling
'after_widget' => '</div>', //Set the element after  your widget to match what your  theme's widgets are using
'before_title' => '<h3>', //Also match the before and after element for the widget's title
'after_title' => '</h3>'
));

2. Call your new widget by adding the PHP code below to the appropriate file, in this case the single.php file. This can be added anywhere that you would like your dynamic widget content to appear.

<?php if (!dynamic_sidebar('post_top')) : ?>
<?php endif; ?>

3. Style your new area to your liking. Reference the classes or ids that you setup in step one to style your content.

div.post_top {
margin: 10px 0;
background: #ccc;
border-radius: 10px; /* in a perfect world */
}

I hope that was painless enough and please check back again for more quick WordPress tutorials.

Like what you are reading? Subscribe to receive monthly tips & updates!

A Monthly Roundup of Articles and a Sweet Deal

Get the latest tips, tricks, tutorials and freebies in your inbox once a monthly.

Join our growing community of front-end web developers and designers. We are constantly publishing new industry tips, tricks and tutorials to help you take your game to the next level. We are also going to include a freebie or deal on something cool each month. Enter your email below and you will only receive this email once a month, nothing else.

Subscribe to our mailing list

* indicates required


    Today in Web Design - Tutorials
    Tagged | , , , ,