1

I created an img shortcode (e.g. [img attachment="19"]) that I want to render in real time in TinyMCE visual editor. So, I created a plugin for TinyMCE that replaces the shortcode in real time. Here is a portion of the Javascript code I wrote (inspired by this tutorial):

(function() {
    tinymce.create('tinymce.plugins.mypluginname', {

        init : function(ed, url) {
            var t = this;

            t.url = url;

            //replace shortcode before editor content set
            ed.onBeforeSetContent.add(function(ed, obj) {
                obj.content = t._do_spot(obj.content);
            });

            //replace shortcode as its inserted into editor (which uses the exec command)
            ed.onExecCommand.add(function(ed, cmd) {
                if (cmd ==='mceInsertContent') {
                    tinyMCE.activeEditor.setContent(t._do_spot(tinyMCE.activeEditor.getContent()));
                }
            });

            //replace the image back to shortcode on save
            ed.onPostProcess.add(function(ed, obj) {
                if (obj.get)
                    obj.content = t._get_spot(obj.content);
            });
        },

        _do_spot : function(co) {
            return co.replace(/\[img([^\]]*)\]/g, function(match, b) {
                const regexp = /[0-9]+/g;
                const res = regexp.exec(b);
                const attachment_id = res[0];

                const url = ...;

                return '<img src="' + url + '" class="wpSpot mceItem" title="img' + tinymce.DOM.encode(b) + '" />';
            });
        },

        ...
}

The problem is that to set the url in the method _do_spot it's necessary to make an asynchronous call, so in the return immediately after the value is not yet available and the shortcode is not replaced correctly. Do you have any suggestions on how I could solve the problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.