By

FitPro 2.3 Released, Here are the New Features

We have just released the latest version of our fitness WordPress theme, FitPro. The new version (2.3) includes many improvements and bug fixes under the hood, but also some significant updates to existing features.

Thanks to our members who gave us feedback, many of the things you requested are in this release!
Read More

By

How to Reuse the Post Editor in WordPress

If you have been following along with the development of WordPress 3.3 beta you may already be aware of the great new function wp_editor(). It really is a game changer. The WordPress core team deserve a real pat on the back for this one. So what’s all the fuss about?

The problem before WP 3.3 was that if you wanted to reuse the built-in editor, used on posts and pages, you had a real battle on your hands to get it to work. It was just too much hassle for the benefits gained.

In fact, the last time I looked into this I gave up and included the CKEditor JS library instead, as that was really easy to implement. This worked pretty well but not really ideal as the CKEditor library is quite weighty to include with your theme/Plugin.

What I REALLY wanted was be able to use the built-in editor that shipped with WordPress. And now I can! The new wp_editor() function has made the hideously difficult task of re-using the editor ridiculously easy. It’s just so easy now to throw editors at every text area in the WP admin you can shake a stick at, and it will work reliably and consistently every time. How cool is that?

In this post I’ll be creating a simple Plugin and show you how to add two separate instances of the WP editor on the Plugin options page. You will be able to grab the code for the whole Plugin at the end of the post.

But first, please bear with me whilst I go through the motions of setting up the Plugin structure. Don’t worry we’ll get to the good stuff soon enough. With this in mind I’m not going to go through every fine detail of the functions needed to set-up a Plugin. I just want to focus on the reusability of the WP editor.

First, let’s register our settings, as we will be using the WordPress Settings API to handle our Plugin options. The code for this is pretty straightforward.

1
2
3
4
5
// Init plugin options to white list our options
function wpet_init(){
	register_setting( 'wpet_plugin_options', 'wpet_options', 'wpet_validate_options' );
}
add_action('admin_init', 'wpet_init' );

Now we need an admin page for our Plugin. Again, this is standard stuff.

1
2
3
4
5
// Add menu page
function wpet_add_options_page() {
	add_options_page('WP Editor Test', 'WP Editor Test', 'manage_options', __FILE__, 'wpet_render_form');
}
add_action('admin_menu', 'wpet_add_options_page');

This will add a Plugin options page under the Settings top level menu with the title ‘WP Editor Test’. Now for the good part.
We need a function to render the form, but let’s break this down a bit. To start with, the Plugin options form uses the post method, with option.php used for the action attribute. Inside the form tags, and before any form fields are rendered let’s add two lines of code to handle all the Settings API details for us.

1
2
settings_fields('wpet_plugin_options');
$options = get_option('wpet_options');

Now we can render all our form fields safe in the knowledge that the Settings API is looking after us and giving us all the correct values and settings. We just need one Plugin option for now, a simple text area.

1
<textarea id="wpet_options[textarea_three]" name="wpet_options[textarea_three]" rows="7" cols="150" type='textarea'><?php echo $options['textarea_three']; ?></textarea>

All we need to do now is add a form submit button so all the loading/saving of the text area content will be handled for us! Sweet.

1
2
3
4
5
6
7
8
9
<p class="submit"><input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" /></p>
</p>
 
OK, so this is all fine and good for bog standard text areas but what about using the funky WP editor as a replacement? This is way easier than you might think. You’re gonna love this.
Simply replace the text area tag above with:
 
<pre lang="php" line="1">
$args = array("textarea_name" => "wpet_options[textarea_one]");
wp_editor( $options['textarea_one'], "wpet_options[textarea_one]", $args );

Basically, all you need to do is call the wp_editor() function and pass it an ID and some optional arguments. The first parameter is the actual content of the text area which we are pulling from the options db table, via the Settings API. Next we add in the ID of the text area as the second parameter. Finally, the third parameter accepts an array of settings you can use to customise the editor.

In this example we are just specifying one array parameter in $args which sets the name of the text area too. These are both the same in this case so we could have actually left this out altogether, as ‘textarea_name’ defaults to the ID name. I explicitly left it in as it’s a good idea to see what’s happening, on a first exposure.

Note: There is currently no WordPress Codex page for wp_editor() at the time of writing (November, 2011) so you will have to dig around the WordPress core to find out more about the parameters available.

Right, want more editors? You got it. We can easily add another instance of the WP editor. Check this out:

1
2
$args = array("textarea_name" => "wpet_options[textarea_two]");
wp_editor( $options['textarea_two'], "wpet_options[textarea_two]", $args );

Just make sure that you change the ID and name parameters to point to a new text area and bingo, we have two separate instances of our editor. That’s almost too easy!

You might have noticed that when we defined the register_setting() function the third parameter was specified as the ‘wpet_validate_options’ callback function. This is a validation function that you can pass your text area content through as it is saved. The callback is defined in the Plugin as:

1
2
3
4
5
6
function wpet_validate_options($input) {
	// Sanitize textarea input (strip html tags, and escape characters)
	//$input['textarea_one'] = wp_filter_nohtml_kses($input['textarea_one']);
	//$input['textarea_two'] = wp_filter_nohtml_kses($input['textarea_two']);
	return $input;
}

I have commented out the lines to validate and strip HTML tags as I want to keep the formatting. This validation function is really useful when you DO want to remove tags from text areas.

The full Plugin code is shown below. Copy it into a text file, save it as wp-editor-test.php, and add to your ‘/wp-content/plugins/’ folder. Just activate it, and visit the Plugin options page under the Settings menu.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/*
Plugin Name: WP Editor Test
Plugin URI: https://www.presscoders.com/
Description: Test Plugin to get the WP editor working on a Plugin admin page.
Version: 0.1
Author: David Gwyer
Author URI: https://www.presscoders.com
*/
 
// Init plugin options to white list our options
function wpet_init(){
	register_setting( 'wpet_plugin_options', 'wpet_options', 'wpet_validate_options' );
}
add_action('admin_init', 'wpet_init' );
 
// Add menu page
function wpet_add_options_page() {
	add_options_page('WP Editor Test', 'WP Editor Test', 'manage_options', __FILE__, 'wpet_render_form');
}
add_action('admin_menu', 'wpet_add_options_page');
 
// Render the Plugin options form
function wpet_render_form() {
	?>
	<div class="wrap">
		<div class="icon32" id="icon-options-general"><br></div>
		<h2>WP Editor Test</h2>
		<form method="post" action="options.php">
			<?php settings_fields('wpet_plugin_options'); ?>
			<?php $options = get_option('wpet_options'); ?>
 
			<table class="form-table">
				<tr>
					<td>
						<h3>TinyMCE - Editor 1</h3>
						<?php
							$args = array("textarea_name" => "wpet_options[textarea_one]");
							wp_editor( $options['textarea_one'], "wpet_options[textarea_one]", $args );
						?>
					</td>
				</tr>
				<tr>
					<td>
						<h3>TinyMCE - Editor 2</h3>
						<?php
							$args = array("textarea_name" => "wpet_options[textarea_two]");
							wp_editor( $options['textarea_two'], "wpet_options[textarea_two]", $args );
						?>
					</td>
				</tr>
				<tr>
					<td>
						<h3>Textarea - Editor 3</h3>
						<textarea id="wpet_options[textarea_three]" name="wpet_options[textarea_three]" rows="7" cols="150" type='textarea'><?php echo $options['textarea_three']; ?></textarea>
					</td>
				</tr>
			</table>
			<p class="submit">
			<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
			</p>
		</form>
	</div>
	<?php	
}
 
// Sanitize and validate input. Accepts an array, return a sanitized array.
function wpet_validate_options($input) {
	// Sanitize textarea input (strip html tags, and escape characters)
	//$input['textarea_one'] = wp_filter_nohtml_kses($input['textarea_one']);
	//$input['textarea_two'] = wp_filter_nohtml_kses($input['textarea_two']);
	//$input['textarea_three'] = wp_filter_nohtml_kses($input['textarea_three']);
	return $input;
}

Note: The code in this post applies to WordPress 3.3 beta 2 which may see some tweaks to the way wp_editor() works before final release. So if you implement any code from this post in your own Plugins then make sure it still works in WP 3.3 final.

By

Enqueue Scripts and Styles on CPT Editor Page

I’ve finally(!) got around to using custom post types, and I’m having a blast. I really wish I had looked into them sooner, they are so cool. The possibilities really are endless, and boost the capabilities of WordPress significantly.

Anyway, this post is about an interesting problem I ran into whilst creating my first CPT (custom post type). The editor for the CPT in question is only ever going to be used to enter a couple of sentences, so it really only needs to have a small height. The default height is way to big and so the other meta boxes on this CPT are pushed down the page.

The solution? Well, it is fairly easy to add custom CSS that will target just the post.php or post-new.php pages in the WordPress admin. However this has the side effect of altering the post editor for ALL post types. Not great.

So, I spent some time looking for a reasonable way that I could enqueue styles that would work for specific CPT’s. After a bit of experimentation I came up with a solution that I could probably reuse. So I created a wrapper function for wp_enqueue_style() that you can use to pass your CPT name along with the usual enqueue parameters, and it will magically enqueue your style ONLY on the CPT editor page that you specify! Cool huh?

Right, let’s take a look at some code..

First off, let’s target the general admin editor pages to run a callback function when either the post.php or post-new.php are loaded. This is pretty standard stuff.

1
2
add_action("load-post.php", array( &$this, 'custom_post_type_editor' ) );
add_action("load-post-new.php", array( &$this, 'custom_post_type_editor' ) );

The custom_post_type_editor() callback function is where we add the call to our enqueue function.

1
2
3
4
5
6
7
function custom_post_type_editor() {
	$cpt = 'my_custom_post_type'; /* Custom post type. */
	$handle = 'my_style';
	$src = get_template_directory_uri().'/css/my_style.css';
 
	wp_enqueue_admin_cpt_style( $cpt, $handle, $src );
}

Aha! This isn’t the usual wp_enqueue_style() function. Like I said earlier, it is a wrapper function. We call the new enqueue function as you do the normal wp_enqueue_style() function, except you also pass in the CPT name as the first parameter. The CPT name is the same one that you specified in register_post_type(). The new enqueue function supports all the usual parameters plus the additional one for the CPT name you want to target.

OK, now for the good stuff. The all important new enqueue function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public function wp_enqueue_admin_cpt_style( $cpt, $handle, $src = false, $deps = array(), $ver = false, $media = 'all' ) {
 
	/* Check the admin page we are on. */
	global $pagenow;
 
	/* Default to null to prevent enqueuing. */
	$enqueue = null;
 
	/* Enqueue style only if we are on the correct CPT editor page. */
	if ( isset($_GET['post_type']) && $_GET['post_type'] == $cpt && $pagenow == "post-new.php" ) {
		$enqueue = true;
	}
 
	/* Enqueue style only if we are on the correct CPT editor page. */
	if ( isset($_GET['post']) && $pagenow == "post.php" ) {
		$post_id = $_GET['post'];
		$post_obj = get_post( $post_id );
		if( $post_obj->post_type == $cpt )
			$enqueue = true;
	}
 
	/* Only enqueue if editor page is the correct CPT. */
	if( $enqueue )
		wp_enqueue_style( $handle, $src, $deps, $ver, $media );
}

Let’s step through what this function does.

  • Firstly, you will notice that you’ve got access to all the parameters available in the normal wp_enqueue_style() function. This is important for general use even though I am not using all the parameters in my particular CPT.
  • Next we reference the global $pagenow variable to grab the current admin page we are on, and initialize an enqueue flag variable to null.
  • This is followed by two tests for the admin page being viewed. The first test checks for new posts being created that are of a specific post type. If it finds a match with the one you passed in it sets the enqueue flag to true.
  • The second test is slightly more tricky as we need to test the post ID of the post being edited on post.php and check it matches our CPT.
  • If either test is successful the enqueue flag is set and our style sheet is enqueued ONLY on the post editor associated with our specified CPT!
  •  

    Whilst I was at it I couldn’t do a wrapper function for wp_enqueue_style() and not do one for wp_enqueue_script()! So here is the equivalent function for enqueueing scripts on a specific CPT admin editor page.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    
    public function wp_enqueue_admin_cpt_script( $cpt, $handle, $src = false, $deps = array(), $ver = false, $in_footer = false ) {
     
    	/* Check the admin page we are on. */
    	global $pagenow;
     
    	/* Default to null to prevent enqueuing. */
    	$enqueue = null;
     
    	/* Enqueue script only if we are on the correct CPT editor page. */
    	if ( isset($_GET['post_type']) && $_GET['post_type'] == $cpt && $pagenow == "post-new.php" ) {
    		$enqueue = true;
    	}
     
    	/* Enqueue script only if we are on the correct CPT editor page. */
    	if ( isset($_GET['post']) && $pagenow == "post.php" ) {
    		$post_id = $_GET['post'];
    		$post_obj = get_post( $post_id );
    		if( $post_obj->post_type == $cpt )
    			$enqueue = true;
    	}
     
    	/* Only enqueue if editor page is the correct CPT. */
    	if( $enqueue )
    		wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer);
    }

    Call this function in the same place as we did for wp_enqueue_admin_cpt_style() with:

    1
    
    wp_enqueue_admin_cpt_script( $cpt, $handle, $src );

    That’s it! I found these functions really useful and I know I will be re-using them again in the future. I hope you find a use for them too. Let me know in the comments if you do, I will be interested to hear.