Honey Bee Hive logo

Honey Bee Hive

A web design & development blog

Adding widgets to your WordPress site

Various widget pictures

If you don’t want to have everything hard-coded into your various pages for your WordPress site, you can use widgets instead. Using widgets can keep the code on your php pages much cleaner, as you only have to add one simple line of code per widget.

Let’s say you have three separate areas on your website’s homepage that contain information on services, phone number and email address and social media links. Each of these areas can be contained within a separate widget area. But first, you have to enable these widget areas in your functions.php file.

To do this, you would add code (found at the top of this page) to your functions.php file, making sure to change the name of the function itself, the widget ‘name’, ‘id’, etc. to whatever would make sense for your site.

Once you have done this and saved your functions.php file, log in to wp-admin for your site and navigate to “Appearance” > “Widgets.” You should see a widget on the right side labeled whatever you put for the ‘name’ in the functions.php file. If you wanted to add some services, you could add a Text box here and put a title on the widget, which will appear on the website above your services information. You can then add any text or html code here that you wish.

To get this widget to appear on your site, you would have to open the page you want the widget to appear on, such as your index.php file if it’s for the homepage, and add dynamic_sidebar(‘widget-sidebar’); inside php tags, making sure to change the information inside the parentheses to whatever ‘id’ you gave this widget in the functions.php file.

Once this simple line of code is placed on your index.php page (or whatever page you wish the widget to be on), the information you placed in this widget from your wp-admin page will now appear.

To add other widgets, simply duplicate the code in your functions.php file that is inside your blank_widgets_init() function (or whatever you decided to call it) and change the information as appropriate for that widget (‘name’, ‘id’, ‘description’, etc.). Then you would simply add the one line of php code for the dynamic_sidebar on whatever page you wish that widget to appear, again, just making sure to change the ‘id’ inside the parentheses to reflect the correct widget. And of course, you can add whatever information you like into the other widget from your wp-admin page.

SHARE IT
Share on FacebookGoogle+Tweet about this on Twitter