Stop WordPress From Removing HTML Comments In Content

This is due to a very old WordPress HTML Comment bug, that was never fully fixed.

You may use Gutenberg, it handles HTML comments better.

Also, This Post suggests that placing a beginning HTML comment TAG, just before the ending HTML comment tag works. Like this:

<!-- some HTML Comment <!-- -->

This is valid HTML comment, but in my tests, this works sometimes, but shows erratic behaviour other times.

As the bug still exists and marked to be fixed for WordPress 5.0 (set as milestone), I guess you may still find some erratic behaviour.

Shortcode fix:

If the HTML comment is too important for you, then you may use a shortcode to place the comment consistently. For example, use this sample plugin (modify it according to your needs):

<?php
/*  
Plugin Name:  WPSE HTML Comment Shortcode
Plugin URI:   https://wordpress.stackexchange.com/a/312622/110572
Description:  WPSE Shortcode check
Version:      1.0.0
Author:       Fayaz Ahmed
Author URI:   https://www.fayazmiraz.com/
*/

remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 99 );
add_filter( 'the_content', 'shortcode_unautop', 100 );
function wpse312622_html_comment( $attr, $content = "" ) { 
    return $content;
}   
add_shortcode( 'comment', 'wpse312622_html_comment' );

Then, use the [comment] shortcode in HTML/TEXT mode like below:

Some Content
[comment]
<!--
This is
<div> comment!</div>
OK -->
[/comment]
Some other content.

In Visual mode, you’ll only see:

Some Content
[comment]
[/comment]
Some other content.

But it’ll not break over save or mode change.

Leave a Comment