Archived topic
Insert element in to blog posts
7 replies · Started by Dana on December 21, 2018
Is it possible to use a hook element to auto insert something in to blog posts after x number of paragraphs?
Thanks!
Hi there,
you can't hook the content but you can filter the_content - try this PHP snippet it adds a block of HTML after the second paragraph to all posts.
add_filter( 'the_content', 'insert_content_after_p', 20 );
function insert_content_after_p( $content ) {
ob_start();
?>
<div>HTML goes here...</div>
<?php
$after_p_content = ob_get_clean();
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $after_p_content, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_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 );
}
Hi David, Sorry life got busy! Where would I add this to make it work please?
It just takes over sometimes :)
Its PHP - this article covers the options:
Yay! I used the code snippet plugin (because the functions.php on my child theme wouldn't save properly) and it worked perfectly!
Thank you
Glad to be of help
Hi David,
The solutions works!
But it can only be used once.
I tried creating new snippet, but gotten this error:
The snippet has been deactivated due to an error on line 3:
Cannot redeclare function insert_content_after_p.
Anything I should do differently?
Hi there,
thats correct you can only register a function once.
If you want to add more inserts then only duplicate this part of the code:
add_filter( 'the_content', 'insert_content_after_p', 20 );
function insert_content_after_p( $content ) {
ob_start();
?>
<div>HTML goes here...</div>
<?php
$after_p_content = ob_get_clean();
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $after_p_content, 2, $content );
}
return $content;
}
In this code you will see 2 instances of:
insert_content_after_p
In your duplicate function you will need to change them both to something else eg. insert_content_after_p_number_two