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.
Source: https://gist.github.com/hirejordansmith/36a220666e64f827067f1f19b4734b49
Thanks, you saved a plugin for me.
Hey Sridhar,
I’m not sure if you still support this topic, but I really need to ask you.
Is there a way to insert the widget before a specified paragraph instead of after?
Thank you so much for this.
Thank you, Sridhar (once again), this was very helpful. I put three instances in the function.php file, and changed the paragraph numbers on each. For anyone who wants to try this, you’ll need to:
change the function name on the second and third set of code (I added “_2” and “_3” the ends)
NOT include the “custom_insert_after_paragraph” function within each additional set. One set works fine for all instances
change the id name of each widget (of course, I added “-2” and “-3”)