4elements, Amsterdam, Holland

  1. Dynamically Adding Four Footer Widget Areas

    These days, many WordPress themes have a number of widget areas in the footer, meaning you can create a "fat footer" with multiple widget areas side by side. It's something I use on all of my themes.

    But what if your theme has four widget areas but you only want three widgets? If you're not careful, you'll end up with an ugly gap on the right-hand side where the empty fourth widget area is.

    In this tutorial I'll show you how to avoid this using a combination of conditional tags in PHP and some Object-Oriented CSS (OOCSS), which will check how many widget areas you've populated and automatically resize them so they each take up the right proportion of the page's width.

    What You'll Need

    To follow this tutorial, you'll need:

    • a development installation of WordPress
    • your own theme to which you'll add the code
    • a code editor

    Registering the Widget Areas

    The first step is to register the four widget areas for your footer. If you don't already have any widget areas registered, you'll need to add this code to your functions.php file:

    This will add four footer widget areas to your theme. If you view the Widgets screen you'll see them all there, along with any others you've already registered:

    Adding the Widget Areas to Your Theme

    If you add widgets to those widget areas now, nothing will happen. You need to add them to your theme's footer. I'll work through the code you need to add to your footer file in stages, adding more checks for different numbers of populated widget areas as we go along.

    Note that you may need to alter some of the classes and elements containing the widget area code in line with your theme's structure and layout.

    1. Checking if No Widget Areas Are Populated

    The first step is to check if no widget areas are populated, in which case nothing should be output. Open your theme's footer.php file and add the code below.

    2. Checking if All Widget Areas Are Populated

    Next, I'll check if all of the widget areas are populated. If this is the case, the theme will output the contents of all four, with each of them floated next to each other and taking up a quarter of the width of the screen. I'll add the classes for this here, but add the CSS to my stylesheet later.

    After the line reading return; but before the endif; statement in the code you just added, add this:

    This does the following:

    • Checks that all footer widget areas are populated using if tags.
    • If so, opens a new element called <aside class = "fatfooter">. This extra element containing the widget areas allows the whole footer to be centred on the page even if the footer itself isn't (for example if the whole footer has a wide background).
    • Outputs all four widget areas using the dynamic_sidebar() function, giving each of these classes for layout.

    The classes are .left.quarter for most of the widget areas, except for the last one which has .right.quarter.

    3. Checking if Just Three Widget Areas Are Populated

    The next step is to add the code to output the widget areas if just three of them are populated. Below the code you just added, insert the following:

    This checks if the first three widget areas are populated and the fourth isn't, and then outputs the first three using appropriate classes—replacing .quarter with .one-third.

    Note that when you're populating your widget areas, you always need to miss out the last one(s) if you don't want to use them all, or this check won't work. Don't leave the first one empty and populate the later ones.

    4. Checking if Just Two Widget Areas Are Populated

    To output just two widget areas if they've been populated and the third and fourth ones haven't, add this code below the code you just added:

    This works in a similar way to the previous two code snippets, using the .half class for layout.

    5. Checking if Just One Widget Area is Populated

    The final check is for just the first widget area being populated. Add this below the code you just added:

    This will output the one widget area's contents in a full-width element.

    Now save your footer.php file.

    Adding the CSS

    Right now your widget areas won't work correctly—in fact, if you populate them all they'll appear one below the other at full width. So you need to add some OOCSS to make those layout classes work. The OOCSS I'm adding is responsive, so I've included media queries to resize the footer widget areas on small screens.

    1. Adding Floats

    First let's make sure the widget areas float alongside each other.

    Open your theme's style.css file and add this code:

    2. Adding Widths

    The widths will ensure that all of the widget areas take up the correct proportion of the screen. I'm using percentages as it makes the code more flexible and responsive. Add this to your stylesheet:

    Note that the widths don't add up to 100% because space needs to be allowed for margins.

    3. Adding Margins

    Now add the styling for margins to your stylesheet:

    Note that the margins are different for elements which also have the .right or .left classes applied to them, so that they sit flush at the edge of their containing element.

    4. Adding Media Queries

    The media queries will do two things:

    • On small screens such as tablets, four elements will appear in a two by two grid, meaning that elements with the .quarter class will have half width and margins will be adjusted accordingly.
    • On very small screens such as smartphones, all elements will be full width.

    Add the media queries at the bottom of your stylesheet along with any other media queries you may have:

    Now save your stylesheet.

    Testing Your Code

    Now it's time to see what happens when you populate your widget areas.

    Below is a screenshot of a site I manage which makes use of this code. Normally the footer has four widget areas:

    Footer with four widget areas

    If I remove the widget from the fourth widget area, just three are displayed, with equal widths:

    Footer with three widget areas

    And if I remove widgets from the third widget area, visitors will see two widget areas each taking up half of the width:

    Footer with two widget areas


    This technique is useful if you want your theme to allow for the population of multiple footer widget areas but you don't know how many of those widget areas will actually be used.

    If you're creating a framework, a starter theme, or a theme which other people will use for their sites, it can help make the footer layout tidier and save extra work down the line adding layout CSS.



    Leave a comment › Posted in: Daily

    1. Design Patterns: The Simple Factory Pattern

      When you think of a factory, what comes to mind? For me, it's a place where things are created - that is, it's a centralized placed where things are produced. Later, the delivery of said products are done by the factory based on an order.

      Let's say that you're requesting a car. A factory will create one based on the specifications of the work order and will then deliver it once it's complete.

      Just as their real world counterparts, a software factory (that is, software that implements the factory design pattern), is an object that is responsible for creating and delivering other objects based on incoming parameters. 

      There are three variations of the factory pattern:

      1. Simple Factory Pattern. This allows interfaces for creating objects without exposing the object creation logic to the client.
      2. Factory Method Pattern. This allows interfaces for creating objects, but allow subclasses to determine which class to instantiate.
      3. Abstract Factory Pattern. Unlike the above two patterns, an abstract factory is an interface to create of related objects without specifying/exposing their classes. We can also say that it provides an object of another factory that is responsible for creating required objects.

      The Problem

      Let's assume that you have a car class that contains all properties and methods relevant to a automobile. In it's most basic form, you'd create it like this:

      Immediately, as time goes there needs to be some change in how the Car object is being created. We need to create class objects that are based on Cart Type instead of just Car. So you need to make changes in all the places where you have created object of this Car class. 

      But, as time goes by, there will inevitably need to be changes in how the Car object is created. For example, we need to create classes based on a Car type rather than just Car. As such 

      Instead of doing that, it would be a better decision to create a class that implements the Factory pattern. 

      The Solution

      In the previous section we recognized that we were creating an object of type Car using the new keyword. And later, it is decided to create an object of the Car class, but based on the Car type like Sedan, SUV, etc.

      Either we should place the Car type class creation code at all places whenever required or implement Factory to handle it in an effective manner. Please refer below code block which shows the implementation of the Simple Factory Pattern.

      In the above class, you can see that we have one static method available which is responsible to create the object based on the type you pass. Now we need concrete classes of different car types like what we have listed below:

      At this point, we have our factory and concrete classes ready to use, so let's practice it for creating require car type objects.

      Addition of New Class

      The addition of a new class is simple: Create one concrete class and you are ready to go. For example:


      When it comes to the factory pattern, consider the use of new keyword to create a new object as harmful. The factory allows us to have a centralized location well all of our objects are created.



      Leave a comment › Posted in: Daily

    1. Creating Your WordPress Knowledge Base’s Front End

      In the previous part of this series, I showed you how to register custom taxonomies for your knowledge base and deregister the ones you don't need.

      The next step is to create the front end, by creating and/or editing any template files we need and adding functions for custom navigation.

      What You'll Need

      To follow this tutorial, you'll need

      • a development installation of WordPress
      • a text editor
      • a starting theme

      1. Creating Template Files

      If you'll remember, in the first part of this series when we planned the knowledge base, we identified the following templates:

      • index.php
      • page.php
      • archive.php
      • single.php
      • sidebar.php

      The starter theme I'm using already includes all of these, which is great news. I will need to edit sidebar.php, to enable the context-sensitive navigation which was part of the original plan. I'll come to this shortly.

      If you're using your own theme and it doesn't include all of those template files, you'll need to create them. Alternatively, if your index.php or loop.php file (if you have one) includes the code necessary for effectively displaying single posts and taxonomy archives, you might want to stick with that.

      I'm not going to work through each of the template files, but let's have a quick look at archive.php to see how it works in my theme:

      As you can see, the template uses object-oriented CSS to set the widths of elements and allows for the display of featured images if the post has one. In a knowledge base, you're less likely to use featured images but it's not impossible so I'll leave those in. If posts don't have featured images, the title and excerpt will still be displayed.

      2. Creating the Sidebar Navigation

      The next step is to create the context-sensitive navigation in the sidebar. I'm not going to add this to the sidebar.php file; instead, I'll add an action hook to that file and then create a function which I'll attach to that action hook.

      Creating the Action Hook

      Open your theme's sidebar.php file. Mine looks like this:

      At the moment this just includes the widget area. I want to keep this but add a hook above it.

      Above the if ( is_active_sidebar() ) line, add the following:

      This creates an action hook using the do_action() function. Any functions you attach to that hook will be fired at that point in your template file, so anything displayed via the hook will show up before the widget area. If you'd rather have the hook below the widget area, just add the code after the widget area instead.

      Creating Functions

      When I was planning my knowledge base, I identified three lists I'd need in different sidebars:

      1. links to the archive pages for the user topic taxonomy terms
      2. links to the archive pages for the developer topic taxonomy terms
      3. links to the archives for the content type taxonomy terms

      Each of these needs to include conditional tags so they're added to the sidebar on the right pages. They can all be included in one function but with a number of conditional tags.

      So let's write them!

      Note that as some of the conditional tags will be detecting static pages, you'll need to create three static pages before you start: for users, developers and content types.

      The User Topics List

      First up is a list of user topics. This includes a link to the main archive page for the taxonomy at the top.The first step is to create the function, and inside it add a conditional tag to check which part of the site we're in.

      Open your functions.php file and add the following:

      This creates an empty function with our first conditional tag, and attaches it to the tutsplus_sidebar hook we added to the sidebar.php file.

      Now add the content inside your conditional function so it reads as follows:

      This outputs a list of terms in the User Topics taxonomy, with links to their archive pages, under a heading, using the following WordPress functions:

      Note that the is_page(  31 ) check will need to have a different page ID depending on the ID of the Users page you've created.

      The Developer Topics List

      Now below the conditional tag for the user topics list, and still inside the tutsplus_sidebar_content() function, add the code for the developer topics, which is very similar:

      The Content Types List

      Finally, add the code for the content types, still inside the tutsplus_sidebar_content() function:

      Your entire function will now look like this:

      You'll now find that as you create posts and assign taxonomy terms to them, the terms will show up in the relevant sidebar.

      Note that any terms without posts assigned to them won't be output, so don't be surprised if your lists are empty at first.

      After you've done this and added some posts, your sidebars will display a list of taxonomy terms depending on where you are in the site. On the Users page (and user taxonomy term archives), you'll see the user topics list:

      User topics list

      When in a term archive in the developer topics taxonomy, you'll see a list of all of the terms in that taxonomy with posts associated with them:

      Term archive

      And on the home page and single pages you'll see a list of all of the terms:

      List of terms


      Your knowledge base now has a front-end structure with the templates and functions in place to support it.

      If you wanted to, you could take some of these techniques further to add additional navigation to your site. For example, you could:

      • add a list of the latest posts to the sidebar on single post pages
      • add a list of the terms which the current post has to the sidebar on single post pages
      • create a page template for your users, developers and content types pages to display the latest posts in each of the terms for each taxonomy

      You may be able to think of more that are relevant to your own knowledge base, but these should give you a taste of the possibilities.

      In the final part of this series, I'll take you through the steps needed to make your knowledge base live and the considerations you'll need to take into account.



      Leave a comment › Posted in: Daily

    1. Writing Documentation for Your WordPress Theme Framework

      So, you now have a WordPress theme framework. Congratulations! The hard work you've put into developing it will pay off in the long run and make your development process smother, more streamlined and more efficient.

      But you need to do one last thing before you're finished, and that's to document your framework. At the very least you'll need to ensure good commenting is used throughout your code, but it's also helpful to write some other documentation so you can keep track of the files, functions and filters that make up your framework's API.

      The options I'll cover are:

      • Commenting
      • Creating a readme file
      • Using automated documentation tools
      • Creating a wiki
      • Creating a website
      • Creating tutorials or recording videos

      Note that while I'll be mentioning a few documentation tools, this tutorial doesn't serve as a recommendation as I haven't used them for my own framework, so you'll need to make your own judgement as to their suitability.

      Writing Quality Comments

      Comments are particularly important when other developers will be working with your code (for example if you're part of a team or if you'll be releasing your framework). But they're also invaluable if you're working on your own, as it's very easy to forget exactly what a piece of code does when you come to edit it a year or more down the line.

      Imagine you've used your framework to build a client site. Two years from now, the site develops a problem at 5:30 on a Friday afternoon. Good comments can make the difference between fixing the problems quickly and being home for the weekend, versus slogging through hundreds of lines of code and missing your Friday night out.

      Here are some tips for good comments:

      • Use comments at the beginning of your file to explain what the file does. For example, in template files include a note about what data it displays and any customizations you’ve made to the loop or other parts of the file; and in plugin files add a note regarding its functionality. For example. the comment below tells users the name of the template file, what it does, the theme it is part of (@package), and which version of the theme it has been in place since (@since). You should use a similar system for plugin files.
      • Use comments to demarcate the sections of your code, not only in stylesheets but also in your theme template files and functions file.
      • Comment anything that is nonstandard.
      • Comment anything that took you a while to work out — use detailed comments so when you come back to it, you don’t have to think it through again.
      • Comment anything that you know someone else will be working on — for example, if your theme files contain scripts that you’ll be asking another developer to perfect, add comments explaining where they apply in the site.
      • Use wording in your comments that you can find using a search later — so don’t abbreviate, and use terms others would understand.
      • Whenever you comment out some code, add a comment to yourself containing the reason. That way, if you forget to remove the code after you’ve finished, or want to add it back in the future, you’ll know what’s going on.
      • When in doubt, add a comment!

      Creating a Readme File

      A readme.txt file is the next level up after commenting. It's a single file which you include in your theme, containing information about the theme.

      The code bundle to accompany this series includes a simple readme.txt file:

      If you want to make your readme file more user-friendly, you might want to consider creating a readme.html file instead which will open in a user's browser. You can use CSS to brand your readme file and make it easier to read.

      If you want to release your theme to the public via the WordPress theme repository, you will be expected to provide a readme.txt file as a minimum form of documentation. I'll cover this in more detail in the final tutorial in this series, on releasing your theme framework.

      Using Automated Documentation Tools

      If you plan to continue developing your framework and don't want to spend a lot of time manually writing documentation for every new feature, an automated documentation tool may be the answer.

      Most of these involve using specific tags or syntax to enable the system to identify where to generate documentation. Examples include:

      If you are going to use one of these tools, it's worth spending some time identifying the best one for you before you start, as you won't be able to transfer your documentation from one to another. 

      But once you've come to grips with the system and got it set up, an automated tool like these can save you a lot of time and can avoid gaps in your documentation down the line, as you'll be so busy writing code you don't have time to update your docs.

      Creating a Wiki or Website

      This option will be more work and is only worth doing if you see your framework growing over time and gaining a significant user base. All of the major theme frameworks have their own websites with documentation, which is either freely accessible or available only to members.

      The website to support your framework could form part of your monetization strategy - the hybrid theme framework, for example, is free, but the documentation and support on its accompanying website are only available to paying subscribers.

      Alternatively if you're releasing your framework as a premium product, you could require subscribers to login to the docs, or you could choose to make your documentation public in the hope that it will encourage more people to buy.

      If your framework is completely free, you might choose to create a free website with documentation, as is the case with the Wonderflux framework:

      Alternatively, you might decide to create a wiki, which has the advantage of letting your users contribute to the docs. This will take more time to set up than a website in most cases, but could be a valuable tool for the community using your framework. You can create a wiki using a plugin for your framework's WordPress site.

      Creating Tutorials or Recording Videos

      Tutorials can help new users, in particular those who can't write code, get to grips with your framework quicker than standard documentation. Videos take this a step further, providing an easy to use visual guide and a great marketing tool.

      The Genesis framework has a range of tutorials for users which are only available to paid subscribers:

      My own Edupress framework has a number of tutorial videos which I created to help users with a varying degree of computer experience and little experience of using WordPress:

      These are displayed on the public website and also in users' dashboards so they can easily access them while working with the framework. If you create documentation, tutorials or videos for your framework, you might include a screen in the dashboard with details of the your docs.

      However, creating tutorials or videos is very time consuming and needs a lot of work to get right: badly written tutorials or poorly produced videos will reflect badly on your framework and may do you more harm than a simpler form of documentation. 


      Whoever's going to be using your theme framework, some sort of documentation is essential. Whether you're just developing the framework for you and your team, or releasing it for wider use, you'll need to record information on the file structure and the API.

      The options I've discussed above range from the simple comments to the more complex videos, with everything in between. What you decide to do will depend on the needs of your users, and may well change over time as you gain a larger user base.



      Leave a comment › Posted in: Daily

    1. Creating Your Own Widgets Using Various WordPress APIs: Introduction

      Final product image
      What You'll Be Creating

      Widgets are a neat way of giving site owners some control over the look (and sometimes functionality) of their WordPress sites. In this series, we are going to be creating a handful of WordPress  widgets by combining the Widgets API with other external APIs.

      The series will consist of the following tutorials:

      1. An Introduction
      2. Related Posts Widget
      3. Login Widget
      4. FAQ Widget
      5. Most Popular Posts Widget with Google Analytics Integration
      6. Physical Address Widget with Google Maps Integration
      7. Conclusion

      In this tutorial, I will introduce you to the WordPress Widgets API by (re)creating a simple text widget. We will dissect and examine the different functions that make up the widget so as to understand how WordPress widgets work in general.

      This widget will also serve as a basis on which we will build on when creating other widgets in the subsequent parts of this series.

      WordPress Widgets

      WordPress widgets add content and features to your sidebars or widgetized areas of your theme. Widgets are designed to provide a simple and easy-to-use way of giving design and structural control of the WordPress theme to the user without requiring them to know how to code.

      Most WordPress widgets offer customization and options such as forms to fill out, optional images and other customization features.

      Examining The Widget Class

      The easiest way to create a WordPress widget is to inherit the WP_Widget class. This way you can use the built-in functions to update the widget, display the widget, and create an admin interface for the widget.

      To fully understand how widgets work, we will create and examine an empty widget. We will then define each function that makes up the widget so see how they work together to create a working widget.

      Our Widget Definition

      The Functions in Detail

      Let's look at each function in more detail:


      This function registers the widget with WordPress


      This function is responsible for the front-end display of the widget. It outputs the content of the widget


      Processes the widget options on save. Use this function to update your widget (option). This function takes two parameters:

      1. $new_instance – Values just sent to be saved. These values will be coming from the form defined within the form() method
      2. $old_instance – Previously saved values from the database

      Be sure to sanitize all user submitted values here. User-submitted values must always be sanitized before being sent to the database


      The form() method/function is used to define the back-end widget form – which you see in the widgets panel in the dashboard  This form enables a user to set up the title and other options for the widget.

      This function takes the following parameter(s):

      • $instance – Previously saved values from the database

      Creating Our Widget

      To create our widget, we will follow the following steps:

      • Define what we are creating
      • Register our widget with WordPress
      • Build the back-end form
      • Save values to the database
      • Define the front-end Display
      • Register the widget

      What Are We Creating?

      As we mentioned earlier, we are creating a simple text widget that enables a user to enter a title and some arbitrary text that will then be output in the front-end of their website where the widget is placed.

      Widget Constructor

      The constructor enables us to initialize our widget by overwriting the parent class (standard WP_Widget class).

      In the code above, we call the parent WP_Widget class's construct function and pass it the foolowing arguments:

      • Base ID - A unique identifier for the widget. Must be in lower case. If left empty a portion of the widget's class name will be used.
      • Name - This is the name for the widget displayed on the configuration page (in the dashborad).
      • And an (optional) array containing a classname and a description. The description is shown on the configuration page (in the WordPress dashboard).

      Building the Back-end Form

      The back-end form will consist of two fields – a title field and a textarea field. Here is a screenshot of the form as it will look in the Widgets panel:

      Our widgets back-end configuration form

      To generate the above form, we would start with pure HTML and then replace some attribute values with some PHP variables and expressions. The following is the HTML code to create the two fields:

      To move from this to our final code for the form() function, we will need to make some of the attributes above dynamic – namely, name, id and the label’s for attribute (which has to match the id of the HTML that the label is for). We will also replace the value of the text field and the content of the textarea field with dynamic values from the database if they have been saved already.

      Here is the code we end up with:

      The code above accesses and assigns previously saved values from the database to two variables – $title and $message. We then use the esc_attr() to encode the returned values and to avoid breaking our code. We then echo the $title attribute into the value attribute of the text field and echo $message as the content of the textarea field.

      In the code above, you will notice two methods that are probably new to you – get_field_id() and get_field_name().

      • get_field_id() – Takes field name as an argument and constructs id attributes for use in form() fields. It ensures that the returned field id is unique
      • get_field_name() – Takes field name as an argument and constructs name attributes for use in form() fields. It ensures that the returned field name is unique.

      The label tags’ for attribute is coded to echo out the id value of the elements they label.

      The widefat class is used to ensure that your widget’s fields have the same look as other fields throughout the WordPress dashboard.

      Updating Our Widget (Options)

      To update our widget, we will write appropriate code in the update method. Here is our code:

      The above function takes two parameters – $new_instance and $old_instance

      • $new_instance is an array containing the new settings (of this instance of the widget) that have just been entered by the user via the backend form which we define in the form() function.
      • $old_settings is an array containing old settings. These are the values that are currently stored in the database.

      The update() function returns an array of settings to save or false to cancel saving.

      In the above code, we assign $old_instance to the $instance variable and replace its title and message keys with values from $new_instance. By returning the new and updated array, we effectively update our widget settings.

      The strip_tags() function removes HTML and PHP tags from a string that’s passed to it. We include this function to avoid a situation where the users of your theme fail to close tags entered via the back-end form, resulting in your site breaking (not rendering properly).

      Defining The Front-End

      The widget() function is responsible for the fron-end display of the widget. It takes two parameters – $args and $instance.

      $args is an array passed to the register_sidebar() function when defining the sidebar/widgetised area in which the widget is placed. This is found in your functions.php file. Below is an example of a register_sidebar() declaration:

      Sample register_widget declaration

      The array contains definitions of the opening and closing tags for the widget itself and for the widget’s title.

      $instance is an array containing the settings for the particular instance of the widget. These settings will have been retrieved from the database.

      We make use of the tags mentioned above in the final widget code below:

      In the above code, we finally get to code the front-end of our widget. Our widget simply outputs a title and some arbitrary message (text). The code does exactly that and wraps the widget itself and the widget’s title inside opening and closing tags defined in functions.php for the specific widget area (sidebar) where the widget is placed.

      We introduce the extract() function which some may not be familiar with. This function takes an associative array and returns its keys as variables. It enables us to echo out $before_widget instead of $args['before_widget'], thus simplifying our code a little.

      The final output on an actual website will look like something like this:

      Our text widget on an actual site

      Registering the Widget

      The widget has to be registered with WordPress after it is defined so that it becomes available in the widget panel of our WordPress dashboard.

      The Final Code

      To keep things simple for the end users of our widgets, we are going to wrap our widget code in a WordPress plugin so that it is easy to install.

      This will also enable us to keep all the code we will be creating throughout the series in a single file.

      Here is the final code:


      In this tutorial, we introduced the series – Creating Your Own WordPress Widgets Using Various APIs. We took a deeper look at what they are, how they work and how to create one.

      The purpose of this tutorial was to provide a thorough introduction to the Widgets API and to provide a base widget from which the other widgets in this series can be created.

      In the next part of the series, we are going to create a related posts widget. In the meantime, please feel free to leave any questions or comments in the form below.



      Leave a comment › Posted in: Daily

  • Page 1 of 44 pages  1 2 3 >  Last ›
  • Browse the Blog