Note that there are some explanatory texts on larger screens.

plurals
  1. POwordpress the_content() formating naked text nodes
    primarykey
    data
    text
    <p>I was looking at the source output of the WordPress function the_content(), and noticed that the html formatting was strange.</p> <pre><code>&lt;div&gt; &lt;p&gt; &lt;inline element&gt; 'text node' &lt;/inline element&gt; &lt;/p&gt; 'text node' &lt;p&gt; &lt;inline element&gt; 'text node' &lt;/inline element&gt; &lt;/p&gt; 'text node' &lt;/div&gt; </code></pre> <p>I was using a php DOM parser editing textContent, and found that all of the text nodes except those in inline element tags were not in a p tag. So they are textContent of the div tag that contains the content.</p> <p>I was wondering if this was my fault or if wordPress just has bad output. I think it would be unlikely for such a widely used cms to have such a basic formatting issue.</p> <p>EDIT : I still don't know if other theme developers have found this issue with wordPress. in any case I wrote a small snip-it to fix it.</p> <pre><code>function setDOM(){ $html = get_the_content(); $html = trim( preg_replace( '/\s+/', ' ', $html ) ); $dom = new DOMDocument; $dom-&gt;loadHTML($html); $xpath = new DOMXpath($dom); $textNodes = $xpath-&gt;query('//text()'); foreach($textNodes as $textNode){ $parent = $textNode-&gt;parentNode; if (($parent-&gt;nodeName !== 'em') &amp;&amp; ($parent-&gt;nodeName !== 'strong') &amp;&amp; ($parent-&gt;nodeName !== 'a') &amp;&amp; ($parent-&gt;nodeName !== 'dt')) { $txt = $textNode-&gt;textContent; $newP = $dom-&gt;createElement('p'); $newTxt = $dom-&gt;createTextNode($txt); $newP-&gt;appendChild($newTxt); $parent-&gt;replaceChild($newP, $textNode); } } $dom-&gt;saveHTML(); return $dom; } $dom = setDOM(); echo $dom-&gt;saveHTML(); </code></pre> <p>I am admittedly a PHP novice and any tips or feedback on that snip-it would be appreciated.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload