How to make WordPress and TinyMCE accept tags wrapping block-level elements as allowed in HTML5?

Question

Starting with version 5 the HTML standard allows <a> tags wrap block-level elements. On a specific page I need to wrap a heading and an image with an <a> tag:

Some intro text.

<div>
  <a href="http://somewhere/">
    <h4>Some heading</h4>
    <img src="http://somewhere/some-img.jpg" alt="Some image" />
  </a>
</div>

While I can enter this in the text editor it causes some strange behavior:

The code above will be transformed into this HTML code:

<p>Some intro text.</p>
<div>
<a href="http://somewhere/"></p>
<h4>Some heading</h4>
<p><img src="http://somewhere/some-img.jpg" alt="Some image" /><br />
</a>
</div>

Obviously, the opening <a> followed by a closing </p> for a never opened <p> is plain wrong. Also there’s some non-closed <p> tag before the <img> tag.


Since this seems to be a newline-related issue, I tried to remove newlines from my WordPress code:

Some intro text.

<div><a href="http://somewhere/"><h4>Some heading</h4><img src="http://somewhere/some-img.jpg" alt="Some image" /></a></div>

Interestingly, this results in the following HTML code:

<p>Some intro text.</p>
<div><a href="http://somewhere/"><br />
<h4>Some heading</h4>
<p><img src="http://somewhere/some-img.jpg" alt="Some image" /></a></div>

Now, there’s still a closing </p> tag missing after the <img>. (Okay, HTML5 accepts non-closed <p> tags… but I don’t think that this behavior is used intentionally here.) Also, WordPress introduces a <br /> that comes out of nowhere.

So far to the WordPress-related issues…


Now to the TinyMCE-related issues:

When switching back from the text edit mode in WordPress to the visual edit mode, the <a>s are still there. However, when switching back to text mode again (or saving the page from visual edit mode) the <a>s get completely removed.


Having this explained, let’s come to my main question: How can I make WordPress and TinyMCE accept <a> tags wrapping block-level elements?


Here’s what I’ve already tried:

I also found the ticket “Block <a> tags are getting stripped from the Editor“, but don’t really understand if stripping <a> tags is considered intentional behavior there.

0
, , , Hauke P. 3 years 2020-06-01T17:10:58-05:00 0 Answers 108 views 0

Leave an answer

Browse
Browse