Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wp_editor Tiny MCE getContent doesn't return content of HTML view

I am using wp_editor in a plugin I am developing and have noticed that .getContent() does not get the contents of the editor if it is in HTML view (as opposed to the visual editor).

If the editor is loaded in HTML view it will return

    tinyMCE.get(inputid) is undefined

But even if I try to get the content via:

    jQuery("#"+inputid).html() or jQuery("#"+inputid).val()

It returns null. Whats convfusing me even more is if the editor is loaded in visual mode, switch to HTML view, make some changes and then use .getContent() it will return the value of the visual editor before any changes were made.

I am pulling out my limited supply of hair with this one so help would be appreciated!

like image 505
KyleC Avatar asked Dec 06 '22 10:12

KyleC


2 Answers

I was struggling with the same problem. The reason is that the editor in the visual tab is tinyMCE and the editor in the html tab is just a plain textarea. Somehow the tinyMCE editor is not activated when the html tab is active so you need to query the textarea instead. The textarea has the id passed to the wp_editor() function. You can query it using traditional jquery methods.

For example, this code sets a variable named content with the content of the tinyMCE editor if it is activated or with the content of the textarea if the tinyMCE returned nothing (because the HTML tab is selected):

var content;
var editor = tinyMCE.get(inputid);
if (editor) {
    // Ok, the active tab is Visual
    content = editor.getContent();
} else {
    // The active tab is HTML, so just query the textarea
    content = $('#'+inputid).val();
}
like image 64
Nicolas Avatar answered Dec 11 '22 11:12

Nicolas


To make it work 100% i had to do like this:

function get_tinymce_content(id) {
    var content;
    var inputid = id;
    var editor = tinyMCE.get(inputid);
    var textArea = jQuery('textarea#' + inputid);    
    if (textArea.length>0 && textArea.is(':visible')) {
        content = textArea.val();        
    } else {
        content = editor.getContent();
    }    
    return content;
}
like image 43
Pablo S G Pacheco Avatar answered Dec 11 '22 09:12

Pablo S G Pacheco