Switch between Visual and HTML tab freely

Alright so I’ve already updated this question a ton and it’s starting to get overloaded, so I figured I’d write this as an answer even though it isn’t a full one.

Extrapolating from @bueltge’s answer, I actually went back and found his previous post in question. In that post, there was a plugin listed that I’ve never seen before: “Preserved HTML Editor Markup”. This plugin hasn’t been updated in a while, but I just tested it with WP 3.6.1 and it’s fully functional. This plugin automatically takes care of wpautop, provides a unified format for inserting br and p tags within the visual editor, and preserves your markup when switching between tabs.

For my own purposes, I expanded upon this plugin with my own functionality: automatic conversion of any html tags within “<code>” tags to their respective entities on save. This means you can write standard HTML code in code tags within the text tab, and then save it, and all the stuff in the pre tags will convert to entities for proper display on the front end of the site and the visual editor. It’s not the most elegant solution I’ve found yet, but it seems to work. Add this line to your functions.php after activating the plugin:

function code_content_conversion_filter( $content ) {
        return preg_replace_callback( '|<code.*>(.*)</code|isU' , 'convert_entities', $content );
}

function convert_entities( $matches ) {
        return str_replace( $matches[1], htmlspecialchars($matches[1], ENT_QUOTES | ENT_HTML5, 'UTF-8', FALSE ), $matches[0] );
}

add_filter( 'content_save_pre', 'code_content_conversion_filter', 0);

Now, just type any valid HTML in between code tags, and when you save, when the editor pops back up, they’ll all be converted to entities. This allows you to write code quicker. Now, the only thing that’s still an issue is that if you have a “pre” field with a nested code tag and HTML in it, and you go to the visual tab and try to insert a new line into the code, a br tag gets injected into your code tag in the HTML. There has to be an option to disable this in TinyMCE. Regardless, as long as you edit your pre fields from the text tab, you can feel free to switch freely between the tabs, add any content under any tab, save from either tab, and not have to worry about messed up formatting!

This actually solves all 5 points of my initial question. Point 2 is still a little bit flaky, but I believe for most peoples purposes, this takes care of the issue. I do plan on sifting through this plugin at some point and extracting the necessary parts, combining it with my finds, and repackaging it for public download. My goal here is to create a simple one click install plugin that wrks as expected.

Hope this helps everybody!

Leave a Comment