I intend to insert the simple script below in a Wordpress post content through Classic Editor; but whenever I switch to visual mode or publish the post, Wordpress automatically removes the whole code (both HTML tags and script):
<p id="Test"></p>
<script>
var x = 10;
document.getElementById("Test").innerHTML= x;
</script>
To solve the issue, I followed these steps respectively:
1) The following snippet code was added to functions.php- so, now, Wordpress doesn't remove formatted HTML anymore:
function uncoverwp_tiny_mce_fix( $init )
{
$init['extended_valid_elements'] = 'div[*]';
return $init;
}
add_filter( 'tiny_mce_before_init', 'uncoverwp_tiny_mce_fix' );
2) By adding the following code, too, the above script is supposed to run on my post (here, for example, post id=123)
function wpb_hook_javascript() {
if (is_page ('123')) {
?>
<script type="text/javascript">
// My javscript code
</script>
<?php
}
}
add_action('wp_head', 'wpb_hook_javascript');
Everything looks fine and logical, but this method doesn't work. I also deferred the script, but the problem remained. What am I missing here?
To solve the issue, I installed and activated Advanced Editor Tools plugin; then, from settings, checked the box "Keep paragraph tags in the Classic block and the Classic Editor". so now Wordpress doesn't strip out HTML tags and lets me insert scripts directly in the text editor.