Load WordPress Editor Via Ajax Plugin

I have researched several similar questions on stackoverflow about this topic that already have answers.

Some of the answers don’t seem to fully work and some are just over my head.

Read More

I have been reading and reworking my code for over a week so I though I would try asking again with more detail than the other questions had.

I’ve written a very simple WordPress plugin that’s only purpose in life is to load a fully functional editor via ajax.

Here is a screencast of this plugin working (with errors):
http://screencast.com/t/eyrTdbUy

I think that if my question can be answered it will help a lot of people.

Here is exactly what the plugin does.

  1. It loads my custom page template instead of the theme template. In this template there is a editor created with the wp_editor function (to load the required files) and a link to add a new editor.

  2. When you click the “add editor” link a new editor is created using the wp_editor function via ajax then initialized with javascript and new link is added to add another.

This only works if a user is logged in.

I wouldn’t advise installing this on your active website because it will take over your pages. This plugin is for example only so it should only be installed on tester sites.

Here’s the problems…

  1. The first instance of the ajax loaded editor works but there is the following errors when you click the tabs to switch back and forth from visual to text
    “TypeError: e is undefined”
    “TypeError: c is undefined”

The “TypeError: e is undefined” also happens when the first new editor is loaded.

  1. After the first instance is loaded another editor cannot be added.

So my question is… What is wrong with my code?

The plugin is made up of 4 files.

File 1 is the plugin file “load_editor.php” (it just includes the functions):

    include('functions.php');

File 2 is the functions file “functions.php”:

<?
// load custom editor template 
function load_editor_template( $template )
{
    $template = plugin_dir_path( __FILE__ ) . 'template.php';

    return $template;
}

add_filter( 'template_include', 'load_editor_template' );

// load javascript 
function load_editor_scripts() {
    wp_enqueue_script( 'load_editor', plugins_url() . '/load_editor/js/load_editor.js', array(), '', true );
    wp_enqueue_script( 'jquery');
}

add_action( 'wp_enqueue_scripts', 'load_editor_scripts' );

// create new editor
function load_editor_new_editor() {
    $id      = $_POST['id'];
    $number  = $_POST['number'];
    $next    = $number + 1;
    $full_id = $id.$number;

    echo "<h1>Editor $number</h1>";

    $content = '<p>This is example content.</p>';
    wp_editor($content, $full_id, array('textarea_rows' => 3));

    // initiate new editor
    echo "<script>
tinyMCE.execCommand('mceAddEditor', true, $full_id);
tinyMCE.init(tinyMCEPreInit.mceInit[$full_id]);
</script>";

    // create "add new" text
    echo "<div><a onclick="load_new_editor('editor', $next);" href='javascript:void(0);'>Click here</a> to add another editor</div>";

    die();
}

add_action( 'wp_ajax_load_editor_new_editor', 'load_editor_new_editor' );

File 3 is the template file “template.php” :

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Load Editor</title>
<?php wp_head(); ?>
</head>

<body>
<? wp_editor('Ecample content', 'id',  array('textarea_rows' => 3)); ?>

<div id="add"><a onClick="load_new_editor('editor', 1);" href="javascript:void(0);">Click here</a> to add an editor</div>
<div id="editor_container">
<!-- Editors will load here -->
</div>

<script>
<?
echo 'ajaxurl = "'.admin_url('admin-ajax.php').'";';
?>
</script>
<?php wp_footer(); ?>
</body>
</html>

And file 4 is the javascript file “load_editor.js”:

function load_new_editor(id, number){
    // remove click to add
    jQuery('#add').remove();

    var fullId = id + number;

    var data = {
        'action': 'load_editor_new_editor',
        'number': number,
        'id': id
    };

    jQuery.post(ajaxurl, data, function(response) {

        //add new editor
        jQuery('#editor_container').append(response);

    });
}

I’ve also put it on github here:
enter link description here

Thank you so much for any help that you can give. I’ve been trying to get this to work for so long it’s frying my brain. I even hired a programmer via elance and he was unable to get as far as I did.

Related posts

Leave a Reply

2 comments

  1. This is the best I can come up with and I think it is good enough for me.

    Everything is working except the quicktags and I can live without them.

    I removed the javascript from funtions.php

    <?
    // load custom editor template 
    function load_editor_template( $template )
    {
        $template = plugin_dir_path( __FILE__ ) . 'template.php';
    
        return $template;
    }
    
    add_filter( 'template_include', 'load_editor_template' );
    
    // load javascript 
    function load_editor_scripts() {
        wp_enqueue_script( 'load_editor', plugins_url() . '/load_editor/js/load_editor.js', array(), '', true );
        wp_enqueue_script( 'jquery');
    }
    
    add_action( 'wp_enqueue_scripts', 'load_editor_scripts' );
    
    // create new editor
    function load_editor_new_editor() {
        $id      = $_POST['id'];
        $number  = $_POST['number'];
        $next    = $number + 1;
        $full_id = $id.$number;
    
        echo "<h1>Editor $number</h1>";
    
        $content = '<p>This is example content.</p>';
        wp_editor($content, $full_id, array('textarea_rows' => 3));
    
        // create "add new" text
        echo "<div id='add'><a onclick="load_new_editor('editor', $next);" href='javascript:void(0);'>Click here</a> to add another editor</div>";
    
        die();
    }
    
    add_action( 'wp_ajax_load_editor_new_editor', 'load_editor_new_editor' );
    

    Then I changed the following on load_editor.js

    1. Added the quicktags function to get the tabs to work without error
    2. Called tinymce.init with the settings that WordPress uses

    I think that’s it.

    // JavaScript Document
    
    function load_new_editor(id, number){
        // remove click to add
        jQuery('#add').remove();
    
        var fullId = id + number;
    
        var data = {
            'action': 'load_editor_new_editor',
            'number': number,
            'id': id
        };
    
        jQuery.post(ajaxurl, data, function(response) {
    
            //add new editor
            jQuery('#editor_container').append(response);
    
            // this is need for the tabs to work
            quicktags({id : fullId});
    
            // use wordpress settings
            tinymce.init({
            selector: fullId,
    
            theme:"modern",
            skin:"lightgray",
            language:"en",
            formats:{
                            alignleft: [
                                {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'left'}},
                                {selector: 'img,table,dl.wp-caption', classes: 'alignleft'}
                            ],
                            aligncenter: [
                                {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'center'}},
                                {selector: 'img,table,dl.wp-caption', classes: 'aligncenter'}
                            ],
                            alignright: [
                                {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'right'}},
                                {selector: 'img,table,dl.wp-caption', classes: 'alignright'}
                            ],
                            strikethrough: {inline: 'del'}
                        },
                        relative_urls:false,
                        remove_script_host:false,
                        convert_urls:false,
                        browser_spellcheck:true,
                        fix_list_elements:true,
                        entities:"38,amp,60,lt,62,gt",
                        entity_encoding:"raw",
                        keep_styles:false,
                        paste_webkit_styles:"font-weight font-style color",
                        preview_styles:"font-family font-size font-weight font-style text-decoration text-transform",
                        wpeditimage_disable_captions:false,
                        wpeditimage_html5_captions:true,
                        plugins:"charmap,hr,media,paste,tabfocus,textcolor,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs,wpview",
                        selector:"#" + fullId,
                        resize:"vertical",
                        menubar:false,
                        wpautop:true,
                        indent:false,
                        toolbar1:"bold,italic,strikethrough,bullist,numlist,blockquote,hr,alignleft,aligncenter,alignright,link,unlink,wp_more,spellchecker,fullscreen,wp_adv",toolbar2:"formatselect,underline,alignjustify,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help",
                        toolbar3:"",
                        toolbar4:"",
                        tabfocus_elements:":prev,:next",
                        body_class:"id post-type-post post-status-publish post-format-standard",
    
    });
    
    
            // this is needed for the editor to initiate
            tinyMCE.execCommand('mceAddEditor', false, fullId); 
    
        });
    }
    

    Here is a screencast of it working.
    http://screencast.com/t/Psd9IVVY

    If anyone knows how to get the quicktags to show, I would love to know.

    Also, if you spot something wrong with my code let me know.

    I have updated the github if you want to download it here:
    https://github.com/ccbgs/load_editor

  2. ( Answer found here: https://wordpress.stackexchange.com/questions/51776/how-to-load-wp-editor-through-ajax-jquery/192132 )

    1) in functions.php,add:

    add_action('init','my_wpEditOUPUTT'); function my_wpEditOUPUTT(){
        if (isset($_POST['Give_me_editorrr'])){
            wp_editor( '' , 'txtrID_'.$_POST['myNumber'], $settings = array( 'editor_class'=>'my_class',     'textarea_name'=>'named_'. $_POST['myNumber'],  'tinymce'=>true , 'media_buttons' => true , 'teeny' => false,));
            exit;   
        }
    }
    

    2) inside dashboard HTML page:

    <div id="MyPlace"></div> <a href="javascript:myLoad();">Click to load</a>
    
    <script type="text/javascript">
    startNumber = 1;
    function myLoad(){ alert('wait 1 sec');
        startNumber ++;
        jQuery.post('./index.php', '&Give_me_editorrr=1&myNumber='+startNumber ,
            function(data,status){ 
                if (status == "success") {  
                    document.getElementById('MyPlace').innerHTML += data; alert("Inserted!");   
                    tinymce.init({ selector: 'txtrID_'+startNumber, theme:'modern',  skin:'lightgray'}); tinyMCE.execCommand('mceAddEditor', false, 'txtrID_'+startNumber);
                }
        });
    }
    </script>