WordPress – another way to add widgets area (sidebar) below a post

WordPress – another way to add widgets area (sidebar) below a post

Previously I described one method to add custom widgets areas by copying and modifying theme files:

Now I’d like to describe another possibility when it comes to adding widgets area above or below a post or page – by adding the_content filter.

Register new widget area

Let’s start with registering the new area for widgets. As I described previously, it is done in functions.php file in a function I have previously created: my_widgets_init().

There is nothing special, I just replaced ID, title and description of the new area:

PHP
functions.php

Add “the_content” filter

The idea of this approach is to add a filter that will add some contents before or after a post. That filter is named the_content and, as can be read in the documentation, allows modifying the content.

I have used that filter to print my new widgets area below a post. Here is the code:

PHP
functions.php

Let me describe what’s happening here:

  • line 20: I register my filter for the_content: function my_after_post_content will be called to modify the content.
  • line 3: I modify the content only when a single post is displayed (not a list of posts like on the home page) and when my widgets area is not empty.
  • lines 4-15 are my default way of displaying a widgets area (sidebar), as I did in previous posts too.
  • line 16: $content .= $sidebar adds the “sidebar” at the end of the post’s content – this way my widgets will be below the post. If you wanted to add widgets before the post, use: $content = $sidebar . $content.
  • lines 8-10: unfortunately, dynamic_sidebar() function does not return the contents of the widgets, but it prints them directly to the page instead. I was surprised to learn it too, because at first I just appended the return value of dynamic_sidebar() function. Then I got strange “1” outputted in place of the widget. Fortunately, there is a pair of ob_start() and ob_get_clearn() PHP functions that allow intercepting the text that would be printed and store them to a variable $widgets. You can learn more about ob_start() here.

Summary

This method is much better to use in this case, when there is a filter that can be modified. Changing or rewriting parent theme’s pages is more difficult due to:

  • you have to find and copy parent theme’s files;
  • it’s difficult to recognize what was originally and what was your modification;
  • you have to maintain those pages when parent’s theme changes – the child theme’s pages should be updated accordingly.

Learning lessons

dynamic_sidebar() does not return the content of the sidebar, but it prints it to the page buffer

Use a filter when it’s possible and feasible

Leave a Reply

avatar
  Subscribe  
Notify of