2

Looking for a way to make the TinyMCE editor always relative to it's content so that the height of the editor changes accordingly to how much text/images it contains.

There seem to be plugins for TinyMCE for this already, but I'm not sure on how to apply it for the Wordpress version: http://www.tinymce.com/wiki.php/Plugin:autoresize

function init_tinymce_autoresize($initArray){
   $initArray['plugins'] = "autoresize";
   return $initArray;
}
add_filter('tiny_mce_before_init', 'init_tinymce_autoresize');

Does not work.

Ideas?

4
  • Not that it helps answer your question, but you could be clobbering other plugins with that code. In my case, $initArray['plugins'] is already populated when the tiny_mce_before_init filter is called. You may be safer appending ",autoresize" (it seems to be a comma-delimited string) if it's not empty.
    – Hobo
    Commented Nov 17, 2012 at 15:04
  • I had a problem with the editor resizing on every keypress (including cursors). I didn't solve it, but kept a little sanity by adding $initArray['autoresize_max_height'] = '500'; to the init_tinymce_autoresize function above (in case it helps someone else).
    – Hobo
    Commented Nov 17, 2012 at 15:49
  • @Hobo I know I would overwrite other plugins by doing as I initially wrote in the question, that was just for debugging purposes. As autoresize isn't part of TinyMCE for Wordpress it wouldn't work however I tried it. The plugin I wrote below does however work.
    – INT
    Commented Nov 17, 2012 at 16:07
  • fair enough. I'm just grateful for your solution (and timing - I can't believe you only asked this two days ago). Thanks!
    – Hobo
    Commented Nov 17, 2012 at 16:09

2 Answers 2

2

Here's a solution. There's a slight problem as it does not recognize when images are added to the editor.

1: Create a folder with the name tinymce-autoresize in the plugins folder.
2. Create a file in tinymce-autoresize named tinymce_autoresize.php with this content:

function intialize_autoresize_plugin() {
    // Check user permission
    if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') )
        return;

    // Add only in Rich Editor mode
    if ( get_user_option('rich_editing') == 'true') {
        add_filter("mce_external_plugins", "autoresize_plugin_load");
    }
}

function autoresize_plugin_load($plugin_array) {
    $plug = WP_PLUGIN_URL . '/tinymce-autoresize/editor_plugin.js'; 
    $plugin_array['autoresize'] = $plug;
    return $plugin_array;
    }

add_action('init', 'intialize_autoresize_plugin');


3. Create a file in tinymce-autoresize named editor_plugin.js with this content:

/**
 * editor_plugin_src.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 */

(function() {
    /**
     * Auto Resize
     *
     * This plugin automatically resizes the content area to fit its content height.
     * It will retain a minimum height, which is the height of the content area when
     * it's initialized.
     */
    tinymce.create('tinymce.plugins.AutoResizePlugin', {
        /**
         * Initializes the plugin, this will be executed after the plugin has been created.
         * This call is done before the editor instance has finished it's initialization so use the onInit event
         * of the editor instance to intercept that event.
         *
         * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
         * @param {string} url Absolute URL to where the plugin is located.
         */
        init : function(ed, url) {
            var t = this, oldSize = 0;

            if (ed.getParam('fullscreen_is_enabled'))
                return;

            /**
             * This method gets executed each time the editor needs to resize.
             */
            function resize() {
                var deltaSize, d = ed.getDoc(), body = d.body, de = d.documentElement, DOM = tinymce.DOM, resizeHeight = t.autoresize_min_height, myHeight;

                // Get height differently depending on the browser used
                myHeight = tinymce.isIE ? body.scrollHeight : (tinymce.isWebKit && body.clientHeight == 0 ? 0 : body.offsetHeight);

                // Don't make it smaller than the minimum height
                if (myHeight > t.autoresize_min_height)
                    resizeHeight = myHeight;

                // If a maximum height has been defined don't exceed this height
                if (t.autoresize_max_height && myHeight > t.autoresize_max_height) {
                    resizeHeight = t.autoresize_max_height;
                    body.style.overflowY = "auto";
                    de.style.overflowY = "auto"; // Old IE
                } else {
                    body.style.overflowY = "hidden";
                    de.style.overflowY = "hidden"; // Old IE
                    body.scrollTop = 0;
                }

                // Resize content element
                if (resizeHeight !== oldSize) {
                    deltaSize = resizeHeight - oldSize;
                    DOM.setStyle(DOM.get(ed.id + '_ifr'), 'height', resizeHeight + 'px');
                    oldSize = resizeHeight;

                    // WebKit doesn't decrease the size of the body element until the iframe gets resized
                    // So we need to continue to resize the iframe down until the size gets fixed
                    if (tinymce.isWebKit && deltaSize < 0)
                        resize();
                }
            };

            t.editor = ed;

            // Define minimum height
            t.autoresize_min_height = parseInt(ed.getParam('autoresize_min_height', ed.getElement().offsetHeight));

            // Define maximum height
            t.autoresize_max_height = parseInt(ed.getParam('autoresize_max_height', 0));

            // Add padding at the bottom for better UX
            ed.onInit.add(function(ed){
                ed.dom.setStyle(ed.getBody(), 'paddingBottom', ed.getParam('autoresize_bottom_margin', 25) + 'px');
            });

            // Add appropriate listeners for resizing content area
            ed.onChange.add(resize);
            ed.onSetContent.add(resize);
            ed.onPaste.add(resize);
            ed.onKeyUp.add(resize);
            ed.onPostRender.add(resize);

            if (ed.getParam('autoresize_on_init', true)) {
            //  ed.onLoad.add(resize);
                ed.onLoadContent.add(resize);
            }

            // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
            ed.addCommand('mceAutoResize', resize);
        },

        /**
         * Returns information about the plugin as a name/value array.
         * The current keys are longname, author, authorurl, infourl and version.
         *
         * @return {Object} Name/value array containing information about the plugin.
         */
        getInfo : function() {
            return {
                longname : 'Auto Resize',
                author : 'Moxiecode Systems AB',
                authorurl : 'http://tinymce.moxiecode.com',
                infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autoresize',
                version : tinymce.majorVersion + "." + tinymce.minorVersion
            };
        }
    });

    // Register plugin
    tinymce.PluginManager.add('autoresize', tinymce.plugins.AutoResizePlugin);
})();


Activate it and you're done!

1
  • I didi exactly that, inside wp-content/plugins/, then activated the plugins with no error but the TinyMCE textareas don't expand when writing. Commented Oct 26, 2017 at 23:25
0

The Autoresize plugin is already built into WordPress with the name "wpautoresize".

The wpautoresize plugin adds the following TinyMCE editor commands:

  1. editor.execCommand('wpAutoResizeOn') .. enable autoresize
  2. editor.execCommand('wpAutoResizeOff') .. disable autoresize
  3. editor.execCommand('wpAutoResize') .. resize the editor to fit the contents (e.g., after programmatically changing the content)

How to use it

Generate the tinyMCE editor using wp_editor(). This function will generate the full tinyMCE editor (with the "Add Media" and "Visual/Text" buttons at the top). This function also loads the "wpautoresize" plugin for you.

You only need to activate the autoresize-mode once the page loaded. This JS code will do this for you: editor.execCommand("wpAutoResizeOn").

Full code sample

Here is a sample PHP hook which generates a TinyMCE editor and also adds the JS code to instantly enable the autoresize-mode on initialization:

<?php
// Generate the WordPress-TinyMCE editor:
wp_editor('', 'my_editor');

// Output the JS code which enabled the autoresize-plugin on page load:
?>
<script>
tinymce.on('AddEditor', function (inst) {
    inst.editor.on('init', function () {
        inst.editor.execCommand('wpAutoResizeOn');
    });
});
</script>
<?php

Special Case: Autoresize in "teeny" mode

The "teeny" mode does not load the wpautoresize plugin, so you need to manually enqueue the TinyMCE plugin before when calling wp_editor().

You can do this by using the filter teeny_mce_plugins - the filter value is an array of all plugins to load. Simply add the plugin "wpautoresize" to that list.

Full code sample

<?php
// Add this filter BEFORE calling wp_editor():
add_filter( 'teeny_mce_plugins', 'my_add_autoresize_pugin' );

// Generate the Teeny-TinyMCE editor:
wp_editor('', 'my_teeny_editor', [ 'teeny' => true ]);

// Output the JS code which enabled the autoresize-plugin on page load:
?>
<script>
tinymce.on('AddEditor', function (inst) {
    inst.editor.on('init', function () {
        inst.editor.execCommand('wpAutoResizeOn');
    });
});
</script>

// ...

// This filter handler enqueues the wpautoresize plugin in teeny mode:
function my_add_autoresize_pugin( $plugins ) {
    $plugins[] = 'wpautoresize';
    return $plugins;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.