Insert wp_editor on front-end with AJAX?
I'm trying to insert a wp_editor()
into a page on the front-end with AJAX. The code I have right now inserts the wp_editor elements and the needed JavaScript and CSS files, but none of the settings I used initially in wp_editor()
are used when creating this TinyMCE element.
How do I pass the $settings
set in PHP into the dynamically created TinyMCE instance?
I found an old question that seems to answer my question, but I don't understand how it works, and the code gives a PHP Depreciated error.
PHP
function insert_wp_editor_callback() {
// Empty variable
$html = '';
// Define the editor settings
$content = '';
$editor_id = 'frontend_wp_editor';
$settings = array(
'media_buttons' = false,
'textarea_rows' = 1,
'quicktags' = false,
'tinymce' = array(
'toolbar1' = 'bold,italic,undo,redo',
'statusbar' = false,
'resize' = 'both',
'paste_as_text' = true
)
);
// Hack to put wp_editor inside variable
ob_start();
wp_editor($content, $editor_id, $settings);
$html .= ob_get_contents();
ob_end_clean();
// Get the necessary scripts to launch tinymce
$baseurl = includes_url( 'js/tinymce' );
$cssurl = includes_url('css/');
global $tinymce_version, $concatenate_scripts, $compress_scripts;
$version = 'ver=' . $tinymce_version;
$css = $cssurl . 'editor.css';
$compressed = $compress_scripts $concatenate_scripts isset($_SERVER['HTTP_ACCEPT_ENCODING'])
false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
if ( $compressed ) {
$html .= "script type='text/javascript' src='{$baseurl}/wp-tinymce.php?c=1amp;$version'/script\n";
} else {
$html .= "script type='text/javascript' src='{$baseurl}/tinymce.min.js?$version'/script\n";
$html .= "script type='text/javascript' src='{$baseurl}/plugins/compat3x/plugin.min.js?$version'/script\n";
}
add_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'editor_js' ), 50 );
add_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'enqueue_scripts' ), 1 );
wp_register_style('tinymce_css', $css);
wp_enqueue_style('tinymce_css');
// Send data
wp_send_json_success($html);
wp_die();
} add_action( 'wp_ajax_insert_wp_editor_callback', 'insert_wp_editor_callback' );
add_action( 'wp_ajax_nopriv_insert_wp_editor_callback', 'insert_wp_editor_callback' );
JavaScript
$('#insert_wp_editor').on('click', function() {
// Data to send to function
var data = {
'action': 'insert_wp_editor_callback'
};
$.ajax({
url: ajaxURL,
type: 'POST',
data: data,
success: function(response) {
if ( response.success === true ) {
// Replace element with editor
$('#editor-placeholder').replaceWith(response.data);
// Init TinyMCE
tinymce.init({
selector: '#frontend_wp_editor'
});
}
}
});
});