Skip to main content

WordPress Tutorial: Insert Sidebar into Content

In this tutorial you will learn how to insert a dynamic sidebar into the content of your posts and pages. The sidebar is inserted after the first paragraph and will render the widgets you have added to the sidebar from the WordPress widgets admin panel.

This technique is very useful for placing advertisements into your website's content pages without having to update lots of theme files.

The first step is to create a dynamic sidebar within your theme's functions.php file to hold your widgets:

if ( function_exists('register_sidebar') ) {
    register_sidebar(array(
            'name'              => 'Inline Content',
            'id'                => 'inline-content',
            'before_widget'   => '',
            'after_widget'    => '',
            'before_title'      => '',
            'after_title'       => '',
    ));
}

Next, add the following content filter to your functions.php file:

//insert content filter
add_filter( 'the_content', 'insert_content_filter' );
function insert_content_filter( $content ) {
    ob_start();
    $sidebar = dynamic_sidebar('inline-content');
    $new_content = ob_get_clean();
    if ( is_single() && ! is_admin() ) {
        return insert_content( $new_content, 2, $content );
    }
    return $content;
}

//paragraph explode and insert
function insert_content( $new_content, $paragraph_id, $content ) {
    $closing_p = '</p>';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {
        if ( trim( $paragraph ) ) {
            $paragraphs[$index] .= $closing_p;
        }
        if ( $paragraph_id == $index + 1 ) {
            $paragraphs[$index] .= $new_content;
        }
    }
    return implode( '', $paragraphs );
}

To briefly explain what is happening here, the filter captures the dynamic sidebar output as a variable and passes this to the insert content function. The insert content function explodes the post content by using the first occurence of a closing paragraph tag as a delimiter. After this, the sidebar is appended to the content before the remaining paragraphs are appended and returned to the content filter for display to your theme using the_content() or get_the_content(). Nice!

You now have inline widgets on your (single.php) content pages without touching the individual theme files.

Looking for Expert WordPress or Drupal development?

I am a freelance website developer and designer based in the UK. I work as a remote Drupal developer, WordPress developer and Front-end developer for a variety of startups, charities and international businesses in Bristol, Bath, London and Europe. You can learn more about me by visiting my resume page.

Get in touch for a free quote on your next project and if you want to connect me with then check out my LinkedIn profile.