Post code snippets in WordPress

Here is the simplest way to easily add source code to WordPress with the built-in TinyMCE editor. There are a lot of posts of people looking for a simple solution like this. And Many people wrote plugins, that don’t really work. MoxieCode gets badmouthed for a poorly written editor. Well that’s all pretty silly. All we needed to do is read some of TinyMCE’s documentation and figure a clever CSS fix.

At the end, you’ll be able to visually embed code just like:

@ require('../../../wp-config.php');
 function wp_translate_tinymce_lang($text) {  if ( ! function_exists('__') ) {   return $text;  } else {   $search1 = "/^tinyMCELang[(['"])(.*)1]( ?= ?)(['"])(.*)4/Uem";   $replace1 = "'tinyMCELang[121]3'.stripslashes('4').__('5').stripslashes('4')";
   $search2 = "/ : (['"])(.*)1/Uem";   $replace2 = "' : '.stripslashes('1').__('2').stripslashes('1')";
   $search = array($search1, $search2);   $replace = array($replace1, $replace2);
   $text = preg_replace($search, $replace, $text);
   return $text;  } }

No plugins are needed. Minimal code changes are neccesary. And it works.

1. Edit tiny_mce_config.php:

1a. Add the Format select box:
Line 31, starts with “$mce_buttons = apply_filters(‘mce_buttons’, array(‘…”
Append to the end of that array, “, ‘formatselect’, ‘cleanup’, ‘removeformat'”. So you should now have that line as:

$mce_buttons = apply_filters('mce_buttons', array('bold', 'italic', 'strikethrough', 'separator', 'bullist', 'numlist', 'outdent', 'indent', 'separator', 'justifyleft', 'justifycenter', 'justifyright', 'separator', 'link', 'unlink', 'image', 'wp_more', 'separator', 'spellchecker', 'separator', 'wp_help', 'wp_adv_start', 'wp_adv', 'separator', 'formatselect', 'underline', 'justifyfull', 'forecolor', 'separator', 'separator', 'charmap', 'separator', 'undo', 'redo', 'wp_adv_end', 'formatselect', 'cleanup', 'removeformat'));

1b. Use your blog’s style:
Line 43, starts with “$mce_popups_css = get_option(‘siteurl’)…”
Replace lines 43 through 49 with:

 $mce_popups_css = '/[wordpressInstallRoot]/wp-includes/js/tinymce/plugins/wordpress/popups.css'; $mce_css = '/[wordpressInstallRoot]/wp-includes/js/tinymce/plugins/wordpress/wordpress.css, /[wordpressInstallRoot]/wp-content/themes/[yourCurrentTheme]/style.css'; $mce_css = apply_filters('mce_css', $mce_css); /*if ( $_SERVER['HTTPS'] ) {  $mce_css = str_replace('http://', 'https://', $mce_css);  $mce_popups_css = str_replace('http://', 'https://', $mce_popups_css); }*/

1c. Install the Block Format Menu:
In front of line 57, add:

theme_advanced_blockformats : "pre,p,div,h1,h2,h3,h4,h5,h6,blockquote,code",

1d. Modify TinyMCE’s line break behaviour:
Replace lines 72 through 75 with:

 force_p_newlines : false, force_br_newlines : false, convert_newlines_to_brs : false, remove_linebreaks : false,

1e. Modify TinyMce’s pasting behaviour:
Replace lines 76 through 78 with:

 paste_create_paragraphs : false, paste_create_linebreaks: true, paste_auto_cleanup_on_paste : true,

2. Edit your stylesheet for proper viewing in TinyMCE.

By default TinyMCE will pick up the BODY style of your stylesheet. Pretty slick, except that most sites have content in a div or td of a different style. So lets fix that.

2a. Add a style for TinyMCE’s body:
This part really depends on your current wordpress theme. What you need to do is find the style of your content div or td, and apply that to TinyMCE’s window.
At the top of your stylesheet, add:

body.mceContentBody { text-align: left; background: #FFF;}

The contents of this should match the contents of your div or td.

2b. The style of our embedded code:
Add another section to style our blocks of code, similar to:

PRE { background-color:#EFEFEF; border-left:5px solid #DDDDDD; color:#000000; font-family:"Andale Mono","Courier New",fixed-width; font-size:11px; margin:15px 0px 15px 10px; overflow:auto; padding:5px 5px 20px 5px; line-height:1em; width: 530px;}

Of course, you style is to your own taste. But I would suggest only fixed width fonts, non breaking lines, and auto overflow for scrollbars. The bottom padding of 20px is important for the bottom scroll bar. It’s actually a workaround for a particular browser. What to guess which one? I set the width to the width of my div as well, so that in TinyMCE, I get the correct view of it – scrollbars and all.


Enter your post as you normally would. Let TinyMCE go buck wild – making <p> tags all over the place.
For each block of code you pasted, select the block and use the format menu to select ‘Preformatted’. You should see that block of code in all its glory. “Hey, the line breaks are gone!” BloggerSayWha? Don’t fret. Save the post and the line breaks will magically appear.

Enjoy =)

10 Replies to “Post code snippets in WordPress”

  1. Thanks alot this is really a great method to have <code> work for you.
    I tried many different methods plugins, also css method.All failed This one seems to be working fine a big Thumbs UP. Thanks

  2. Nice sollution, but after I follow your tutorial my tinyMCE’s Fonts view become smaller than usual.

    how to make it normal again as usual??

    thx before.

  3. One should note that these are not &quot;minimal code changes&quot; and do affect core files of WordPress which is definately not a way to go if you want to regularily update your WordPress installation. That doesn’t really qualify as an &quot;easy way to add source code to WordPress&quot; to me 😉
    Better use some good plugins like WP-Syntax ( that make use of GeSHi ( No modifications on the core files needed = happy admins everywhere 🙂

Comments are closed.