How to Create Multiple Widgets in WordPress Using For & Foreach Loops

How to Create multiple widgets in WordPressAre you looking for a dynamic way to create multiple widgets in WordPress without writing too much code? Or have you seen a WordPress theme that allows you to create a sidebar or create multiple widgets from the dashboard?

In a previous tutorial, I explained in detail how to add sidebar in WordPress. Today, in this quick tutorial, I will share with you a quick solution to create multiple widgets in WordPress on the fly.  This will not only save your time but you will reuse the trick in multiple projects especially if you are a busy professional WordPress developer.

Loop to Create Multiple WordPress Sidebars

Ideally, we want to use a function that creates the multiple WordPress sidebars using some kind of a loop. When you create this code for the first theme or plugin you are going to reuse it in more theme and plugin development.

This function can also be a basis of building a dynamic sidebar generator used in a theme or a WordPress plugin. For you to understand fully how this code works, you need to be conversant with the process of creating a WordPress sidebar as I explained thoroughly in that post.

Creating WordPress Widgets

WordPress widgets play a crucial role in helping users to display new content in different sections of their website. In this post on how to create widget areas in WordPress; I shared important tips and the code and also explained very clearly in this post on how to add a sidebar in WordPress.

When you have the ability to add a widget in WordPress theme it is simply amazing since you can add any new feature across all sections of your site.

For a quick review of how to add the sidebar or widget area in WordPress the following code should be added to the functions.php to register a sidebar as the first step when adding a widget in your WordPress theme:

/**
* Register widget area.
*/

function njengah_create_one_widget_tutorial() {

//Register Sidebar function - https://developer.wordpress.org/reference/functions/register_sidebar/

register_sidebar(

  array(
     'name'          => __( 'Njengah Widget Example ', 'textdomain' ),
     'id'            => 'sidebar-1',
     'description'   => __( 'Add widgets here to appear in your sidebar.', 'textdomain' ),
     'before_widget' => '<section id="%1$s" class="widget %2$s">',
     'after_widget'  => '</section>',
     'before_title'  => '<h2 class="widget-title">',
     'after_title'   => '</h2>',

   )

  );


}

add_action( 'widgets_init', ' njengah_create_one_widget_tutorial’);

This is the register_sidebar() function that we are using to add one widget to WordPress site and the widget can now be displayed in the respective page template using the dynamic_sidebar() function as follows :

<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>

    <ul id="sidebar">

      <?php dynamic_sidebar( 'sidebar-1' ); ?>

    </ul>

<?php endif; ?>

 Creating Multiple Widgets Sidebars in WordPress

Since the code to register sidebar used register_sidebar() function to create more sidebars you just need to repeat that code several times as you wish: Now we can create three sidebars by repeating this code as follows :

/**
* Register 3 widget areas.
*/

function njengah_create_three_widget_tutorial() {

//Register Sidebar #1

register_sidebar(
   array(
       'name' => __( 'Njengah Sidebar 1 ', 'textdomain' ),
       'id' => 'sidebar-1',
      'description' => __( 'Add widgets here to appear in your sidebar 1.', 'textdomain' ),
      'before_widget' => '<section id="%1$s" class="widget %2$s">',
      'after_widget' => '</section>',
      'before_title' => '<h2 class="widget-title">',
      'after_title' => '</h2>',
  )
);

//Register Sidebar #2

register_sidebar(
   array(
       'name' => __( 'Njengah Sidebar 2', 'textdomain' ),
        'id' => 'sidebar-2',
        'description' => __( 'Add widgets here to appear in your sidebar 2.', 'textdomain' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h2 class="widget-title">',
       'after_title' => '</h2>',
     )
);

//Register Sidebar #3

register_sidebar(
   array(
       'name' => __( 'Njengah Sidebar 3 ', 'textdomain' ),
       'id' => 'sidebar-3',
       'description' => __( 'Add widgets here to appear in your sidebar 3.', 'textdomain' ),
       'before_widget' => '<section id="%1$s" class="widget %2$s">',
       'after_widget' => '</section>',
       'before_title' => '<h2 class="widget-title">',
       'after_title' => '</h2>',
      )
   );

}
add_action( 'widgets_init', ‘njengah_create_three_widget_tutorial’);

You can create more and more widget areas by repeating this code that you are using to register the widgets and everything works and it is cool.

But wait a minute! Haven’t you heard about one fundamental rules or programming – DRY (Don’t Repeat Yourself)?

This is a simple principle that means your code should be efficient and should avoid such repetitions to avoid redundancy. We can replace this code with something better, for example, we can pass an argument to the register_sidebar() function to do it three times.

Create Multiple Widgets in WordPress with an Argument 

We can achieve our goal to create multiple widgets in WordPress by altering the register_sidebar() function by passing an array of arguments as the second parameter and the first parameter is the number of widgets we want to create. In this case, we can alter the code shared above to this:

function create_multiple_sidebar_widgets() {

$args = array(
    'name' => 'Njengah Sidebar %d',
    'id' => 'njengah-sidebar',
    'description' => 'One of the Njengah tutorial sidebars',
    'class' => '',
    'before_widget' => '<li id="%1$s" class="widget %2$s">',
    'after_widget' => '</li>',
    'before_title' => '<h2 class="widgettitle">',
    'after_title' => '</h2>'
 );

  register_sidebar( 3, $args );

}
add_action( 'widgets_init', ‘create_multiple_sidebar_widgets’);

The name value has a placeholder %d that simply allows us to display the sidebars with the numbers 1,2 and 3.

This is a quick solution to create multiple widgets in WordPress but still, it is not the ultimate solution. We can go ahead and improve it as I will demonstrate shortly.

Create Multiple Sidebars with Array in WordPress

The solution above is not very effective since the title and the description are limited to only the ones you assign in the register_sidebar () function.

To make this solution better we can introduce an array with names, ids, and descriptions then we use a foreach loop to register the sidebars.

The following is an example of creating multiple widgets using an array and foreach loop:

function create_multiple_sidebar_widgets() {

$njengah_sidebars = array(
  array(
     'name' => 'Widget Area Homepage',
     'id' => 'widget-area-homepage',
     'description' => 'Widgets shown in the homepage’,
  ),
  array(
      'name' => 'Widget Area Header ',
     'id' => 'widget-area-header',
     'description' => 'Widgets shown in the header',
  ),
  array(
     'name' => 'Widget Area Footer',
     'id' => 'widget-area-footer',
     'description' => 'Widgets shown in the footer',
   ),
  );

   $defaults = array(
      'name' => 'Njengah Sidebar',
      'id' => 'njengah-sidebar',
      'description' => 'The default sidebar is shown on the left side of blog pages in this theme',
       'class' => '',
      'before_widget' => '<li id="%1$s" class="widget %2$s">',
      'after_widget' => '</li>',
      'before_title' => '<h2 class="widgettitle">',
      'after_title' => '</h2>'
  );

  foreach( $njengah_sidebars as $sidebar ) {

    $args = wp_parse_args( $sidebar, $defaults );

    register_sidebar( $args );
   }

}
add_action( 'widgets_init', ‘create_multiple_sidebar_widgets’);

This solution gives you the ability to create multiple widgets in the future since you just need to add every new widget details (name, id, and description ) to the array and the widget is created on the fly.

Create Multiple Similar Footer Widgets in WordPress

Ultimately this is the best approach to creating multiple widgets in WordPress albeit the second option can also come in handy when you want multiple similar widgets.

For example, when you want to create several footer widgets, it can be easier to use the for loop as follows:

/**
* Register widget area using for loop
*
* @author Joe Njenga
*/

function njengah_register_sidebars_dynamically() {

    for ( $i = 1, $n = 5; $i <= $n; $i++ ) {

       register_sidebar(

         array(
               'name' => esc_html__( 'Footer Area #', 'textdomain' ) . $i,
               'id' => 'footer-' . $i,
               'description' => sprintf( esc_html__( 'The #%s column in footer area', 'textdomain' ), $i ),
               'before_widget' => '<aside id="%1$s" class="widget %2$s">',
               'after_widget' => '</aside>',
               'before_title' => '<h3 class="widget-title">',
              'after_title' => '</h3>',
           )
        );
     }
   }
}
add_action( 'widgets_init', 'njengah_register_sidebars_dynamically' );

I think this can be one of the most useful solutions to creating multiple widgets in WordPress since the for loop simply counts to 5 and creates 5 widgets you can just change the number to any other number of widgets you want and the multiple widgets will be generated dynamically on the fly.

Wrapping up

We have covered the three different ways to create multiple widgets in WordPress and I hope this is just a start to give you the impetus to create more innovative ways of creating multiple dynamic sidebars or multiple widgets in WordPress themes and plugins. Finally, it is important for every WordPress developer to learn how to make use of the DRY principle since it not only saves time but it improves code efficiency.

Similar Articles

  1. How to Get Registered Sidebars WordPress with Foreach loop