Widgets are one of the best WordPress tools: you can add a widgetized plugin and show its content in any sidebar in your site. But what happens if you want to show a widget within your post? In this tutorial we will learn how to create a sidebar to be displayed using a shortcode.
Overview
The following video will give you a quick overview of what we’re going to build, how it works and how to use it:
First of all, we need two things: a sidebar and a shortcode.
<?php add_action( 'init', 'ilc_register_sidebars' ); add_shortcode( 'shortbar', 'shortbar_sc' );
Open the functions.php file in your WordPress theme and let’s begin defining our sidebar and shortcode.
Registering the sidebar
Our sidebar definition is the usual one, just remember to add a descriptive title and a good description for the end user.
<?php function ilc_register_sidebars() { register_sidebar( [ 'name' => 'Sidecode', 'description' => 'Widgets in this area will be shown using a shortcode.', 'before_title' => '<h3>', 'after_title' => '</h3>', 'before_widget' => '', 'after_widget' => '' ] ); }
You don’t need to create a different instance of the sidebar.php
file since we won’t be using a PHP file. Instead, we will use the dynamic reference.
Creating the shortcode output
This is where the magic happens. Due to the nature of a shortcode, we can’t just use the dynamic_sidebar
function because its return is echoed and hence the content will be outputted before the post content. We need to return the shortcode content for it to be displayed in the natural flow of the post content.
<?php function shortbar_sc( $atts ) { ob_start(); dynamic_sidebar( 'sidecode' ); $html = ob_get_contents(); ob_end_clean(); return $html; }
To prevent the echo, we capture the output buffer and instead save it in the $html variable to properly return it.
Conclusion
You can now use this going to your Widgets area in the WP Admin and dropping some widgets in the new Sidecode sidebar you should have. Then go to your post and type [shortbar]
to embed the sidebar in your post. Of course, the widgets might appear with no style, since chances are that you’ve created your CSS selectors specifically for widgetized areas in sidebars, instead of post content. Not a big deal, go ahead and add the required selectors to stylize the widgets shown in your content.
This example show how to display all the widgets from an specific sidebar into the post using a shortcode, but if you want to display an specific widget, you could use the_widget function instead in your shortcode to configure the widget and display it within your post content. It won’t allow for easy customization of the widget though, and it’s definitely less user friendly, so if you’re preparing this for a theme to be sold or for a client, you might want to go with the approach outlined in this tutorial and create the sidebar to drag and drop widgets and display them using your shortcode.