0

I have tried preformatted button, Paste as text button or Text tab element before pasting source code, WordPress always stripped indent tabs and broke code formatting.

For example, the source code:

final class HtmlAttr
{
  /**
   * Constructor
   *
   * @param  string  $filter  A filter hook to modify the attribute(s).
   */
  function __construct(array $attrs, $filter = '')
  {
    // Something...
  }

  /**
   * Render attribute(s)
   */
  function __toString()
  {
    // Something...
  }
}

will become:

final class HtmlAttr
{
 /**
 * Constructor
 *
 * @param string $filter A filter hook to modify the attribute(s).
 */
 function __construct(array $attrs, $filter = '')
 {
 // Something...
 }

 /**
 * Render attribute(s)
 */
 function __toString()
 {
 // Something...
 }
}

I'm using Atom IDE and can't figure out the right way to paste source code from IDE into WordPress TinyMCE Editor directly. Really appreciate your help!

6
  • Do you use <pre></pre> around the code?
    – fuxia
    Commented Aug 18, 2016 at 12:35
  • @toscho You meant adding <pre></pre> manually. Isn't it's equal to preformatted button or I have missed something?
    – Minh Tri
    Commented Aug 18, 2016 at 12:40
  • 1
    Well, yes, but that button is available in the visual editor only – which is stripping tabs on paste.
    – fuxia
    Commented Aug 18, 2016 at 12:43
  • If you will use the text mode of the editor, the plugin AddQuicktag enhance optional the editor buttons for mask code and add the pre-tags.
    – bueltge
    Commented Aug 18, 2016 at 13:05
  • @toscho Thank you! That help me understand the problem. I though that WordPress should have a built-in way to handle source code automatically but look like we have to enter pre element each time.
    – Minh Tri
    Commented Aug 18, 2016 at 14:13

2 Answers 2

0

Have you tried another editor?

You could try CKEeditor, according to some it does not mess with the code indents.

https://wordpress.org/plugins/ckeditor-for-wordpress/

1
  • Thank for your response but the plugin is too much for my problem.
    – Minh Tri
    Commented Aug 18, 2016 at 14:16
0

After struggling about adding pre element manually, I decided to create a shortcut button on TinyMCE Editor:

This is button class and hooks in my parent theme:

/**
 * EmbedSourceCodeButton
 *
 * @see  https://codex.wordpress.org/TinyMCE_Custom_Buttons
 */
final class EmbedSourceCodeButton
{
  /**
   * Name
   */
  const NAME = 'embedSourceCodeButton';

  /**
   * Constructor
   */
  function init()
  {
    if ('post' !== $GLOBALS['current_screen']->post_type) return;

    add_action('mce_buttons', [$this, 'addButton']);
    add_action('mce_external_plugins', [$this, 'addPlugin']);
    add_action('admin_enqueue_scripts', [$this, 'localizeLabels'], 10, 0);
  }

  /**
   * Localize labels
   */
  function localizeLabels()
  {
    wp_localize_script('jquery-core', self::NAME, [
      'title'        => __('Embed Source Code', 'textdomain'),
      'listboxLabel' => __('Language', 'textdomain'),
      'textboxLabel' => __('Source code', 'textdomain')
    ]);
  }

  /**
   * Add this button to TinyMCE
   *
   * @see  https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/class-wp-editor.php#L624
   *
   * @return  array  $buttons
   */
  function addButton(array $buttons)
  {
    array_push($buttons, self::NAME);

    return $buttons;
  }

  /**
   * Add this plugin
   *
   * @see  https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/class-wp-editor.php#L392
   *
   * @return  array  $plugins
   */
  function addPlugin(array $plugins)
  {
    $x = SCRIPT_DEBUG ? '' : '.min';

    if ( !isset($plugins[self::NAME]) )
      $plugins[self::NAME] = get_template_directory_uri() . '/assets/js/button' . $x . '.js';

    return $plugins;
  }
}
add_action('load-post.php', [new EmbedSourceCodeButton, 'init']);
add_action('load-post-new.php', [new EmbedSourceCodeButton, 'init']);

And this is button.js which is inside asset/js folder of my theme:

(function() {
  tinymce.PluginManager.add('embedSourceCodeButton', function(editor, url) {
    editor.addButton('embedSourceCodeButton', {
      text: false,
      icon: 'wp_code',
      onclick: function() {
        editor.windowManager.open({
          title: embedSourceCodeButton.title,
          body: [
            { // Unnecessary yet but may be helpful in the future.
              name: 'language',
              type: 'listbox',
              label: embedSourceCodeButton.listboxLabel,
              values: [
                {
                  text: 'PHP',
                  value: 'php'
                },
                {
                  text: 'CSS',
                  value: 'css'
                },
                {
                  text: 'HTML',
                  value: 'html'
                },
                {
                  text: 'Javascript',
                  value: 'javascript'
                }
              ]
            },
            {
              name: 'code_block',
              type: 'textbox',
              multiline: true,
              label: embedSourceCodeButton.textboxLabel
            }
          ],
          onsubmit: function(e) {
            e.stopPropagation();
            var entities = {
              '&': '&amp;',
              '<': '&lt;',
              ">": '&gt;',
              '"': '&quot;',
              "'": '&#39;',
              '/': '&#x2F;'
            };
            // Encode HTML special chars before inserting into editor.
            var codeBlock = e.data.code_block.replace(/&|<|>|"|'|\//gm, function(s) {
              return entities[s];
            });
            editor.insertContent('<pre data-lang="' + e.data.language + '"><code>' + codeBlock + '</code></pre>');
          }
        });
      }
    });
  });
})();

Hope it can help someone who is lazy as me too. ;-)

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.