WordPress: Load wp_editor() through AJAX/jQuery

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.

Shyam has written 29 articles

Shyam is senior full stack developer, who loves to explore new technologies and work on them. He's passionate about coding so can code 24/7. He uses PHP as a backend programming language.

He knows Laravel, MySQL, AngularJS, ReactJS, Redis, Kubernetes, Git, CodeIgniter, PHP, MVC pattern, Lodash, jQuery, VanilaJS, Teamcity and many other technologies and tools.

Shyam writes notes and hacks on his blog (https://shyammakwana.me). In spare time he can be found @ StackOverflow or crafting any new open source application.

Passionate Programmer and Meditator #PERIOD.