WordPress removes empty span tag

Viewed 4915

I use WordPress-editor and I want to display an icon within a "span"-tag like this:

<div id="question1" class="box-around">
   <div class="box-left"><span class="fa fa-search" aria-hidden="true"> </span></div>
   <div class="box-right">
      <h3>Some Heading</h3>
      Some Text
      <span id="question1-answer"> </span>
    </div>
</div>

Whenever I make a change in "visual", it removes the "span"-tag and looks like this:

<div id="question1" class="box-around">
  <div class="box-left"></div>
   <div class="box-right">
      <h3>Some Heading</h3>
       Some Text
       <span id="question1-answer"> </span>
    </div>
</div>

Oddly enough, the span at the bottom (id="question1-answer") is kept. Am I missing something? I already tried to set a whitespace "&nbsp" within the tag, which will be converted to a " " (actual whitespace) after changing text in "visual" and used different tags as well.

Thanks!

3 Answers

A little more specific - allow empty tags if they have an id, name, class or style attribute:

function override_mce_options($initArray) {
  $opts = '*[id|name|class|style]';
  $initArray['valid_elements'] .= ',' . $opts;
  $initArray['extended_valid_elements'] .= ',' . $opts;
  return $initArray;
}
add_filter('tiny_mce_before_init', 'override_mce_options');

Maybe I'm doing something wrong, but for me it works. Still I'm sure there's a better solution - it would be nice to be able to add only one specific tag to valid elements.

With the above answers (Val) the function will allow empty tags but this still may not work due to the theme structure or any page builder plugins you may have.

For example, I am using WPBakery page builder with custom functions. For my to allow an empty span with style (background for example) I added the above code to my functions.php and also placed a
tag within the block.

The span block has a custom class .break to where the styling is created, I then set a display: none on the
tag within the .break class so the styling remains but the extra space is removed.

<span class="break"><br></span>

.break br {display:none;}

Now the empty span tag should display as normal.

Related