Need a WordPress Expert?

Hire me!

May27

Add Native Syntax Highlighting and Line Numbering to Your Plugin with WP 2.8

by John Kolbert | Posted in: WordPress



What it Does

This tutorial teaches you how to add WordPress 2.8’s built-in syntax highlighting and line numbering capabilities to your plugins administrative pages. It requires 2.8 beta and up.

Background

WordPress 2.8 is set to be released in the near future and promises to add quite a few new features. Among them, and one that fellow nerds like me will appreciate, is the addition of syntax highlighting and line numbering to WordPress’ built-in theme and plugin editors. Although I rarely use the built-in editors, it’s a nice addition for those times I need to make a quick change and don’t want to log into my FTP.

What made me figure all this out? While developing a plugin recently I found that the user experience would be improved by including syntax highlighting and line numbering. After trying to integrate a few scripts on my own I thought why not try to use WordPress’ built in feature now?

Well, after a few hours of being elbow deep into WordPress’ admin files, here’s how you can add syntax highlighting and line numbering to your plugin natively. WordPress 2.8 uses an open source project called CodePress to handle the syntax highlighting and we’re able to tap into that script for our own purposes.

Download the Tutorial File

The PHP file is available for you to download, test, and modify: WP Syntax Demo (87)

Step 1: Creating Your Plugin’s Admin Page

First let’s create the administrative page for your plugin. For this example I’ll create a top-level menu page, though you can create your admin page anywhere you like.


function sd_add_pages(){
     add_menu_page('Syntax Demo', 'Syntax Demo', 8, __FILE__, 'sd_content'); //add top level menu page
}

add_action('admin_menu', 'sd_add_pages'); //add options pages

First we create the the menu page by using the add_menu_page function and referencing it through the admin_menu action. See the link below for more info on the add_menu_page function.

Useful Link (opens in new window): Adding Menu Pages – WP Codex

Step 2: Creating Your Textbox

In the add_menu_page function above we referenced a sd_content function. This function will house our textbox that will have the syntax highlighting. First I’ll give you the code then explain a few important details about it.


function sd_content(){
?>
   <div class="wrap">
     <h2>CodeBox: Test Your Code Here</h2>

     <form method="post" action="" id="template" name="template">
        <table class="form-table">
        <tr>
          <td valign="top" style="width: 560px">
            <textarea name="newcontent" id="newcontent" tabindex="1" class="codepress php" rows="15" cols="75"><?php echo $_POST['newcontent'];?></textarea>
             <input style="margin-top: 10px;" class="button-primary" type="submit" value="submit" />
          </td>
        </tr>
        </table>
     </form>
<?php
}

This function merely adds a form with the ID of template, and a textarea HTML element with the ID of newcontent. You must use these IDs when naming your textarea and form. To use different IDs see the Advanced Usage section, below. Also, we gave our textarea a special class of class=”codepress php”. This tell the CodePress script to change this textbox and that the language we want for syntax highlighting is PHP.

Step 3: Enqueue the CodePress Script

In this step we’ll tell WordPress to add the CodePress script to the list of enqueued scrips that WordPress adds. We’ll do this by creating a function that calls wp_enqueue_script.


function sd_header(){
     if($_GET['page'] == "syntaxdemo.php"){
          wp_enqueue_script( 'codepress' );
     }
}

add_action('init', 'sd_header'); //add header info

To make sure that the CodePress script is only added to the page we need, we’ll add a simple check to make sure we’re on our plugin’s settings page. You’ll need to adapt the $_GET['page'] == “syntaxdemo.php” to reflect the actual filename of your plugin. If you plugin is in a folder it would be $_GET['page'] == “folder/syntaxdemo.php”. Also, you’re $_GET['page'] variable may be different depending on how you added your plugin settings page (in our case, as a top-level menu).

Useful Link (opens in new window): Using wp_enqueue_script – WP Codex

Step 4: Finishing the Textbox Input

If we stopped now the textbox we created would have proper syntax highlighting and line numbers. However, you wouldn’t be able to access any of the information that the user enters into the textbox. This is because CodePress actually places an iFrame HTML element over the textbox. Thus all editing is being done in the iFrame and not actually in the textbox we created. We just need to get the value of the textbox from the iFrame and add it to our textbox when the form is submitted.

There are two ways to do this. We can use WordPress’ built in function:


if($_GET['page'] == "syntaxdemo.php"){
      add_action( 'admin_print_footer_scripts', 'codepress_footer_js' );
}

However, this requires the following

  • form ID and name of template
  • textarea ID and name of newcontent

If you follow the above guidlines, then this script will work fine. Note: I followed these guidlines in this example.

Advanced Usage

If you’d rather use your own IDs and names for your form and textarea we can manually add the correct javascript code to the footer. This code is the same as got included in the admin_print_footer_scripts function used above, but we’ll manually change the IDs to reflect our own.


function sd_footer(){
     if($_GET['page'] == "syntaxdemo.php"){
?>  <script type="text/javascript">
          /* <![CDATA[ */
          var codepress_path = '<?php echo includes_url('js/codepress/'); ?>';
          jQuery('#formid').submit(function(){
          if (jQuery('#textareaid_cp').length)
          jQuery('#textareaid_cp').val(textareaid.getCode()).removeAttr('disabled');
          });
          /* ]]> */
      </script>
<?php
     }
}

add_action('admin_footer', 'sd_footer');

There are a few noteworthy things in the above code. Here again we checked to make sure we were on our plugin’s page by using the $_GET['page'] check as we did before. Also, we must change #formid on line 6, above, to the ID we’ve given our form. If the ID is myform, then it would begin jQuery(‘#myform’).

Finally, we must change #textareaid to reflect the actual ID of the textarea we create, making sure to keep the _cp addition were necessary. If we create a textarea with the ID of mytextarea, lines 7-8 in the above code would get changed to the following:

if (jQuery('#mytextarea_cp').length)
jQuery('#mytextarea_cp').val(mytextarea.getCode()).removeAttr('disabled');

That’s It

By following the above instructions we can now include syntax highlighting and line numbering natively in our WordPress plugins. Where could you use this? Some examples might be as custom field boxes on the write post/page screen, or on settings pages for plugins where the user needs to paste or enter some HTML or PHP code. I’m working on integrating it into a few of my plugins. What about you? Do you think it’s worth it?

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

3 Comments

  1. Brendon said:

    Hi,

    Wish I had found this post about an hour ago — would have saved me some time and frustration.

    Would you happen to know how to force line wrapping when codepressed, would you?

    Thanks,
    Brendon.

    on June 29, 2009 at 9:16 am Reply

  2. Andrew A. Peterson said:

    Wow. I am so frustrated.
    I have spent the last four hours trying to find a way for me to endow my clients, whom I have set up with WordPress, with the power of line numbers when editing CSS.

    WordPress is nearly FTP-free, which is great for lay persons.

    I've had great results with teaching older people how to use FireBug to find and preview changes in their CSS by right-clicking on what they want to change and selecting "inspect element."

    And it's not too difficult for many of these folks to get into their Stylesheet in WP's Theme Editor and find and change what they have tested in FireFox.

    But would make the workflow a thousand times better would be a way to make the Textarea in the Theme Editor disply Line-Numbers.

    There are a handful of plugins that claim to do this, but none of them seem to work with WordPress 2.8.4

    And in my hunt, I've found evidence that WP once had this feature briefly, but turned it off because it was too slow. I never noticed it and I've been using WP for years, and have always been up to date.

    Now I find this blog post. Great. A hack to turn on the CodePress functionality in WordPress 2.8… The problem is I don't understand how to do this!

    Can't you just make an installable Plugin? A plugin would be great because it would be nice to be able to turn the thing on and off, if it is indeed slow or buggy.

    Or if some manual intervention with WP's files is necessary, could you please-please-please explain which files you are editing in this tutorial?

    All of the examples show top line numbers (1, 2, 3). There's no "this is what the whole thing should look like" …You don't explain what file or files you are editing.

    This is so annoying because I'm not a programmer and this how-to assumes that we know certain things that I don't know. I could brave these steps if I knew where to make them. I have been searching for this post for hours only to find that I'm not smart enough to understand the directions!!!

    Thanks for your consideration and for sharing information, even if I am ineligible for it.

    on October 20, 2009 at 9:22 pm Reply


RSS feed for comments on this post.

Trackbacks on this post

Links to this post will be listed here. You an add your own by linking to the TrackBack URL

  1. Line-Numbers in WordPress 2.8’s Theme Editor? | andrewapeterson.com

    [...] of a comment I left HERE, a tutorial having to do with adding line-numbers and syntax-highlighting to WordPress’ [...]

Leave a comment



By pressing submit you are granting me a perpetual, non-exclusive licence to reproduce, paraphrase, and display your words, name, and/or website on this domain. All comments subject to moderation at my discretion.