Adding a Custom CSS Editor to Your Theme Using ACE

Adding a Custom CSS Editor to Your Theme Using ACE

Tutorial Details
  • Program: WordPress
  • Version: 3.1 and above
  • Difficulty: Intermediate
  • Estimated Completion Time: 30 minutes to 1 hour

Final Product What You'll Be Creating

Whenever someone downloads your theme and decides that some of the CSS isn’t working for them, they usually go into style.css and manually modify the stylesheet to their liking. This isn’t too hard to do, but it does present an issue when the next release of your theme is available and they decide to update.

All of their changes will then be overwritten. A great work-around is to offer a Custom CSS editor so that all the changes they make will be safely stored in the database and keeping up to date in the future will not be an issue.


The ACE Editor

ACE Editor

Anyone familiar with using a desktop IDE such as Coda, Sublime and Kimodo will be right at home within the ACE editor‘s interface. ACE is a web-based code editor that can easily be embedded into any web page or online app. It features syntax highlighting for over 40 languages and also includes a live code checker to help improve your code as you write.

In this tutorial, I plan on guiding you through the steps needed to get ACE installed in your theme so you can offer this great feature to your users.


Step 1: Installing ACE

The ACE editor is hosted on GitHub, but if you take a look at what you get when you download the project, you might be overwhelmed by the number of files. There are really only three files that we need and you can find them in the download package I provided through the Download link above.

  • ace.js
  • mode-css.js
  • worker-css.js

These three files need to be included in a folder named “ace“. Place this folder in the root of your theme.


Step 2: The Helper File

In order to insert ACE into your theme, you need to create a helper JavaScript file that will set everything up on your page to make the ACE editor work correctly. Create a new file called “custom-css.js” with the following code and add it to the root of your theme as well.

( function( global, $ ) {
	var editor,
		syncCSS = function() {
			$( '#custom_css_textarea' ).val( editor.getSession().getValue() );
		},
		loadAce = function() {
			editor = ace.edit( 'custom_css' );
			global.safecss_editor = editor;
			editor.getSession().setUseWrapMode( true );
			editor.setShowPrintMargin( false );
			editor.getSession().setValue( $( '#custom_css_textarea' ).val() );
			editor.getSession().setMode( "ace/mode/css" );
			jQuery.fn.spin&&$( '#custom_css_container' ).spin( false );
			$( '#custom_css_form' ).submit( syncCSS );
		};
	if ( $.browser.msie&&parseInt( $.browser.version, 10 ) <= 7 ) {
		$( '#custom_css_container' ).hide();
		$( '#custom_css_textarea' ).show();
		return false;
	} else {
		$( global ).load( loadAce );
	}
	global.aceSyncCSS = syncCSS;
} )( this, jQuery );

The code above inserts the ACE editor into the page and makes sure that the CSS your users enter is also entered into the textarea field so that it can be stored in the WordPress database. There is also a check in there for IE7, which is incompatible with ACE so it will just load the basic textarea.


Step 3: Enqueueing the Files

With all the appropriate JavaScript files added, you have to hook into admin_enqueue_scripts to make sure your scripts appear on your Custom CSS editor admin page.

add_action( 'admin_enqueue_scripts', 'custom_css_scripts' );

function custom_css_scripts( $hook ) {
	if ( 'appearance_page_custom_css_admin_page_content' == $hook ) {
		wp_enqueue_script( 'ace_code_highlighter_js', get_template_directory_uri() . '/ace/ace.js', '', '1.0.0', true );
		wp_enqueue_script( 'ace_mode_js', get_template_directory_uri() . '/ace/mode-css.js', array( 'ace_code_highlighter_js' ), '1.0.0', true );
		wp_enqueue_script( 'custom_css_js', get_template_directory_uri() . '/custom-css.js', array( 'jquery', 'ace_code_highlighter_js' ), '1.0.0', true );
	}
}

Step 4: The Custom CSS Editor

Now you need to create your theme option page in the wp-admin where the Custom CSS editor will be displayed. To add a theme option page, you need to hook into the admin_menu action.

Add the following to functions.php:

add_action( 'admin_menu', 'custom_css_admin_page' );

function custom_css_admin_page() {
	add_theme_page( 'Custom CSS',  __( 'Custom CSS' ), 'edit_theme_options', 'custom_css_admin_page_content', 'custom_css_admin_page_content' );
}

You also need to register a Custom CSS settings field so you can store it in the WordPress database. To do that you need to hook into the admin_init action and use the register_settings() function.

add_action( 'admin_init', 'register_custom_css_setting' );

function register_custom_css_setting() {
	register_setting( 'custom_css', 'custom_css',  'custom_css_validation');
}

Since you’ve already added the option page and registered the settings, you can now create the content of your page:

function custom_css_admin_page_content() {
	// The default message that will appear
	$custom_css_default = __( '/*
Welcome to the Custom CSS editor!

Please add all your custom CSS here and avoid modifying the core theme files, since that\'ll make upgrading the theme problematic. Your custom CSS will be loaded after the theme\'s stylesheets, which means that your rules will take precedence. Just add your CSS here for what you want to change, you don\'t need to copy all the theme\'s style.css content.
*/' );
	$custom_css = get_option( 'custom_css', $custom_css_default );
	?>
	<div class="wrap">
		<div id="icon-themes" class="icon32"></div>
		<h2><?php _e( 'Custom CSS' ); ?></h2>
		<?php if ( ! empty( $_GET['settings-updated'] ) ) echo '<div id="message" class="updated"><p><strong>' . __( 'Custom CSS updated.' ) . '</strong></p></div>'; ?>

		<form id="custom_css_form" method="post" action="options.php" style="margin-top: 15px;">

			<?php settings_fields( 'custom_css' ); ?>

			<div id="custom_css_container">
				<div name="custom_css" id="custom_css" style="border: 1px solid #DFDFDF; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; width: 100%; height: 400px; position: relative;"></div>
			</div>

			<textarea id="custom_css_textarea" name="custom_css" style="display: none;"><?php echo $custom_css; ?></textarea>
			<p><input type="submit" class="button-primary" value="<?php _e( 'Save Changes' ) ?>" /></p>
		</form>
	</div>
<?php
}

The only thing missing is some code validation. Since you’re allowing the user to insert CSS, there isn’t much validation you can do but it’s still smart to have this little function in place:

function custom_css_validation( $input ) {
	if ( ! empty( $input['custom_css'] ) )
		$input['custom_css'] = trim( $input['custom_css'] );
	return $input;
}

Step 5: The Front End

Adding the Custom CSS editor to the wp-admin is now taken care of, but the CSS isn’t being displayed on the front end, so it isn’t actually doing anything other than being stored in the database. In order to actually display the CSS on the front end, you need to hook into the wp_head action.

add_action( 'wp_head', 'display_custom_css' )

function display_custom_css() {
	?>
<style>
<?php
$custom_css = get_option( 'tango_custom_css' );
if ( ! empty( $custom_css ) ) { ?>
<style type="text/css">
	<?php
	echo '/* Custom CSS */' . "\n";
	echo $custom_css . "\n";
	?>
</style>
	<?php
}
?>

Conclusion

Many of my customers find the Custom CSS editor to be one of the best features offered in my themes. Taking the time to go through this tutorial to learn how to set one up in your own theme will benefit anyone who uses it. It’s an amazing tool to help users customize your theme without having to worry about compromising their changes when future updates are released.

If you have any comments or feedback on anything you read above, please feel free to discuss it below.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pat Ducat

    Great tutorial! Thanks!

  • Rudd

    Great!
    I hope there’ll be a tutorial on adding custom functions file :)

    • http://www.facebook.com/joell.lapitan Joell Lapitan

      better to convert your “custom functions” to a plugin, so that when you switch to another theme, it will still work

  • Pingback: Wptuts+: Adding a Custom CSS Editor to Your Theme Using ACE | bavotasan.com

  • Roger Campos

    Very Cool!!! Thanks!

  • http://www.wantplugin.com/ WantPlugin

    Thanks! Very helpful for me.

  • http://twitter.com/martinjharvey Martin Harvey

    Sweet! I’d never of thought of tryng this, but might add it into my next theme.
    Greta Stuff.

  • Mark Roberts

    Be careful about using $.browser if you are using the latest version of jquery, it’s been deprecarted.

  • asas

    as

  • http://www.facebook.com/profile.php?id=38009035 De’Yonte W.

    This is awesome. I was just looking for a good CSS editor to integrate with WordPress.

  • Bryan Petty

    If you would like to still use the default theme and plugin editors to change your styles and other things in the theme itself (or the plugin), you could also just install my free plugin that replaces the built-in theme and plugin editors with the ACE editor used here: http://wordpress.org/extend/plugins/better-file-editor/

    I know, a little shameful plug, but I had to given how closely related this article is. :)

    • http://wp.tutsplus.com/ Japh

      LOL Thanks for your input, Bryan. Always good to have an alternative handy :)

  • http://www.mathewporter.co.uk/ Matt Porter

    Sure beats the default editor, makes the mass lines of code become less blurred. Great post.

  • http://www.facebook.com/ashraf.akbar.7 Ashraf Bin Akbar

    Hey nice tutorial but i am having server error in the last step 5!!!!! using wp 3.5

  • Jerome

    Thanks a lot. Was struggling to make it work from their instructions as there is thousands of file.

    One question tho. I cant seem t find those file you have. for example ace.js is completely different in code and in size and cannot find the other file.

    Could you point me to the location please

  • Jerome

    for people who want to have the right link to the file. i stumbled accross this link.

    https://github.com/ajaxorg/ace-builds

    it definitely help understanding and creating my own theme too.
    Hope it helps,
    Jerome

  • http://www.socialstrategy.co.uk/ Terence Milbourn

    OR ~ you can just install Jetpack.