-
-
Save luispaiva/27c6619b030d8b9f1c7682d2f5f54c5e to your computer and use it in GitHub Desktop.
Insert HTML between paragraphs in WordPress post content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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