Site logo

Archived topic

Is there a way to manually place an adsense ad every 3 paragraphs?

6 replies · Started by Heath on November 28, 2022

Viewing posts 1–7 of 7

Just wondering if there is a way to manually add the adsense ad every 3 or 4 paragraphs?

Hi Heath,

A popularly used plugin for such a feature is "Ad Inserter". Reference: https://wordpress.org/plugins/ad-inserter/

Another way is through custom code. Try adding this snippet:

add_shortcode('portable_hook', function($atts){
	ob_start();
        $atts = shortcode_atts( array(
            'hook_name' => 'no foo'
        ), $atts, 'portable_hook' );
		do_action($atts['hook_name']);
	return ob_get_clean();
});

add_filter( 'the_content', 'insert_featured_image', 20 );
function insert_featured_image( $content ) {
    global $post;
    $inserted_hook = do_shortcode('[portable_hook hook_name="after_every_third_paragraph"]');
    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_every_third_paragraph( $inserted_hook, 3, $content );
    }
    return $content;
}
function prefix_insert_after_every_third_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 ( $index % $paragraph_id == 0 ) {
     $paragraphs[$index] .= $insertion;
    }
  }
  return implode( '', $paragraphs );
}

Adding PHP: https://docs.generatepress.com/article/adding-php/#code-snippets

With this, you can add your Advertisement code through a Hook Element, and hook it to Custom Hook - after_every_third_paragraph.

Example: https://share.getcloudapp.com/12uR6w2O

Hook Element reference: https://docs.generatepress.com/article/hooks-element-overview/

Thanks! For the PHP do I need a plugin to update that?

What about every 4 paragraphs instead of every 3? I tried to update the snoppet but got an error so I didn't do something right.

Any suggestions?

Hi there,

on this line:

return prefix_insert_after_every_third_paragraph( $inserted_hook, 3, $content );

Change the 3 to 4 so it becomes:

return prefix_insert_after_every_third_paragraph( $inserted_hook, 4, $content );

This archived topic is closed to new replies.