How to insert a widget area after a specified paragraph in Genesis

This tutorial provides the steps to register a custom “Ad Content” widget area and insert the widget(s) placed in this widget area after a specified paragraph in the content on single posts in Genesis.

Step 1

Add the following in child theme’s functions.php:

// Registers `ad-content` widget area.
genesis_register_widget_area(
    array(
        'id'          => 'ad-content',
        'name'        => __( 'Ad Content', 'text-domain' ),
        'description' => __( 'This is the ad content section.', 'text-domain' ),
    )
);

add_filter( 'the_content', 'custom_insert_widget_area' );
/**
 * Filters the content to insert widget area after specified paragraph of single post content.
 *
 * @param string $content Existing post content.
 * @return string Modified post content.
 */
function custom_insert_widget_area( $content ) {

    ob_start();
        genesis_widget_area( 'ad-content', array(
            'before' => '<div class="ad-content widget-area"><div class="wrap">',
            'after'  => '</div></div>',
        ) );
    $widget_area_html = ob_get_clean();

    if ( is_singular( 'post' ) ) {
        $content = custom_insert_after_paragraph( $widget_area_html, 3, $content ); // change 3 to the paragraph after which you would like to insert the widget area.
    }

    return $content;
}

// Callback function that inserts the passed in HTML after the specified paragraph and returns the modified content.
function custom_insert_after_paragraph( $insertion, $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 ] .= $insertion;
        }
    }

    return implode( '', $paragraphs );

}

In the above change 3 in $content = custom_insert_after_paragraph( $widget_area_html, 3, $content ); to the paragraph number after which the widget area should be inserted.

Step 2

Go to Appearance > Widgets and drag your desired widget(s) into the Ad Content widget area.

This site uses cookies to offer you a better browsing experience. By browsing this website, you agree to our use of cookies.