After searching for hours trying to figure out why the WordPress WYSIWYG code editor TinyMCE kept changing my PHP code I came upon a thread that was a somewhat helpful.   Basically it let me set TinyMCE’s configuration in the WordPress theme which is great for all kinds of things, like if you want more HTML tags in your posts.

What I needed to do however was get TinyMCE to not touch my code when it was inside PHP code or the insert_php shortcode.  To do that I had to modify the protect option in TinyMCE.  Then I had to create a JavaScript regular expression to exempt certain blocks of code from TinyMCE’s parser.  Below is the code I came up with, just add it in the functions.php section of your WordPress theme:

function schema_TinyMCE_init($in)
{
// more things modifying TinyMCE can go here

// for PHP tag and insert_php shortcode (JavaScript regular expressions)
$in['protect'] = "[
/\<\?php[\s\S]*?\?\>/g,
/\[insert_php\][\s\S]*?\[\/insert_php\]/g
]";
return $in;
}
add_filter('tiny_mce_before_init', 'schema_TinyMCE_init' );

It’s got room for improvement, the line breaks don’t always line up correctly.  For the <?php one for some reason you need to put an > on the first line.  So for example the opening line of code would be  <?php  //>   after doing this the editor doesn’t touch the line breaks.

With the knowledge of JavaScript regular expressions you could do things to exempt all kinds of code, not just PHP.

This was tested on WordPress 4.5.3, your mileage may vary for versions further from this.

I just created a plugin based on this you can access here.  Please note that you cannot use the plugin and this fix at the same time.

I Did The Digging So You Don't Have To

I Did The Digging So You Don't Have To

Where should I send my free Web Tools Booklet filled with resources to supercharge your web development workflow?

Your Web Tools Booklet is on its way.