[*]
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="https://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="https://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="https://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="https://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:
- Adding a filter to
tiny_mce_before_init
that sets TinyMCE’svalid_children
setting for<a>
s to include<h4>
s (as suggested in the question “HTML5, WordPress and Tiny MCE issue – wrapping anchor tag around div results in funky output”) - Adding a filter to
tiny_mce_before_init
that sets TinyMCE’sschema
setting tohtml5
.
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.