Site icon Shyam Makwana

WordPress: Load wp_editor() through AJAX/jQuery

wp_editor() ajax shyammakwana

wp_editor() ajax shyammakwana

Simply when we use wp_editor() it loads WordPress default visual editor. But when we are generating form or fields through AJAX call it doesn’t work. I was stuck in same problem in one of my projects. After some research I found easy fix to this problem. This might be helpful to you also. Below is my jQuery code which I have used to call form which has wp_editor()


 

jQuery.ajax({
	url : '',
	data : { product_cat: category , action : 'newproduct_form'},
	method : 'post',
	success : function(form){
		//console.log(form);
		if (form != 0) {
			// remove existing editor instance
			tinymce.execCommand('mceRemoveEditor', true, 'post_content');

			// init editor for newly appended div
			var init = tinymce.extend( {}, tinyMCEPreInit.mceInit[ 'post_content' ] );
			try { tinymce.init( init ); } catch(e){}

		}
	}
});

 

Procedure

It’s clearly seen in code that I have first removed instance of existing editor which is applied in ‘post_content’ class ID. You do not need to add this mceRemoveEditor line if you are calling it in textarea first time.

And in next line I’m initializing new instance on textarea with ID ‘post_content’. That’s It !

Method 2 for initializing wp_editor() (TinyMCE)

     tinymce.execCommand('mceAddEditor', true, 'post_content');

Use above code in your jQuery in AJAX success.

Exit mobile version