Skip to content

Instantly share code, notes, and snippets.

@keesiemeijer
Created September 18, 2016 18:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save keesiemeijer/2f07ab7a3ab7a4ddef49f46c86bd29fb to your computer and use it in GitHub Desktop.
Save keesiemeijer/2f07ab7a3ab7a4ddef49f46c86bd29fb to your computer and use it in GitHub Desktop.
Insert HTML between paragraphs in WordPress post content
<?php
/**
* Insert HTML between paragraphs in WordPress post content using php DOMDocument().
*
* Inserts HTML in the middle of top level paragraphs.
* For example:
*
* <p>Hello</p>
* <blockquote>
* <p>Awesome</p><!-- not a top level paragraph -->
* </blockquote>
* <!-- HTML is inserted here -->
* <p>World!</p>
*/
add_filter( 'the_content', 'insert_HTML_between_paragraphs' );
function insert_HTML_between_paragraphs( $content ) {
/* Edit the HTML variables */
// Block-level HTML element that's inserted between paragraphs (e.g. p, div, etc).
$parent_element = 'p';
// Content for the inserted block-level HTML element.
$parent_content = "I'm <strong>inserted</strong> in the middle of top level paragraphs";
/* That's all, stop editing variables here. */
// HTML to be inserted.
$insert_content = "<{$parent_element}>{$parent_content}</{$parent_element}>";
// nodeDocument for post content
$html = new DOMDocument();
// Load the html from post content.
@$html->loadHTML( $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
// Get paragraphs from post content.
$p = $html->getElementsByTagName( 'p' );
// Get top level paragraph indexes
$nodelist = array();
foreach ( $p as $key => $node ) {
if ( 'body' === $node->parentNode->nodeName ) {
$nodelist[] = $key;
}
}
// Check if more than 1 paragraph is found.
if ( 1 < count( $nodelist ) ) {
// Get position where to insert the HTML.
$position = floor( count( $nodelist ) / 2 );
// nodeDocument for insert HTML.
$insert_html = new DOMDocument();
// Load the html from insert content.
@$insert_html->loadHTML( $insert_content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
// Parent bloc-level HTML element from insert content.
$parent_node = $insert_html->getElementsByTagName( $parent_element )->item( 0 );
// Insert the HTML in the middle of post content.
$p->item( $nodelist[ $position ] )->parentNode->insertBefore( $html->importNode( $parent_node, true ), $p->item( $nodelist[ $position ] ) );
// Convert HTML back to string.
$content = $html->saveHTML();
} else {
// Insert HTML after content if none or only one paragraph is found.
$content .= $insert_content;
}
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment