- This topic has 7 replies, 2 voices, and was last updated 2 years, 10 months ago by David.
-
AuthorPosts
-
December 21, 2018 at 7:32 pm #763407Dana
Is it possible to use a hook element to auto insert something in to blog posts after x number of paragraphs?
Thanks!December 22, 2018 at 6:09 am #763588DavidStaffCustomer SupportHi 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 ); }
May 2, 2019 at 4:46 pm #887220DanaHi David, Sorry life got busy! Where would I add this to make it work please?
May 3, 2019 at 2:41 am #887590DavidStaffCustomer SupportIt just takes over sometimes 🙂
Its PHP – this article covers the options:May 3, 2019 at 9:23 pm #888486DanaYay! I used the code snippet plugin (because the functions.php on my child theme wouldn’t save properly) and it worked perfectly!
Thank youMay 4, 2019 at 3:53 pm #889190DavidStaffCustomer SupportGlad to be of help
June 7, 2021 at 5:10 am #1813230IBNU AHMADHi 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?
June 7, 2021 at 7:18 am #1813366DavidStaffCustomer SupportHi 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
-
AuthorPosts
- You must be logged in to reply to this topic.