By

Deactivating a WordPress Plugin Automatically

With every release of WordPress there are so many cool new features to play with. This usually a good thing but one downside is that if you want to incorporate them straightaway into your Plugin it can break versions of WordPress that haven’t upgraded yet.

I had exactly this issue when adding some new code to my Plugin Options Starter Kit Plugin.

I added two new text areas to the Plugin options form that use the built-in WordPress editor. This is made possible by the fantastic wp_editor() function, which is only available in WordPress 3.3 (see my post on this function here). However, a lot of users who are already running this Plugin may not have upgraded to WordPress 3.3 (when it is released) by the time I post the Plugin update on WordPress.org.

So where does this leave you? How can you safeguard against Plugin incompatibility with a users version of WordPress. You could insert a simple die() function, but we can do better than that!

Check out the code below that generates the above message, safely deactivates the incompatible Plugin, and provides a convenient link back to the WordPress admin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function posk_requires_wordpress_version() {
	global $wp_version;
	$plugin = plugin_basename( __FILE__ );
	$plugin_data = get_plugin_data( __FILE__, false );
	$require_wp = "3.5";
 
	if ( version_compare( $wp_version, $require_wp, "<" ) ) {
		if( is_plugin_active($plugin) ) {
			deactivate_plugins( $plugin );
			wp_die( "<strong>".$plugin_data['Name']."</strong> requires <strong>WordPress ".$require_wp."</strong> or higher, and has been deactivated! Please upgrade WordPress and try again.<br /><br />Back to the WordPress <a href='".get_admin_url(null, 'plugins.php')."'>Plugins page</a>." );
		}
	}
}
add_action( 'admin_init', 'posk_requires_wordpress_version' );

So, what’s going on here?

First, we grab the current version of WordPress stored in the global $wp_version variable. Next, we have two lines of code to store the plugin folder/filename, and the name of the Plugin itself.

Now for the important bit. We use version_compare() to check we are running WordPress 3.3 or higher. If you want to check for a different version just change ‘3.3’ to a different value. If your installed version of WordPress is not compatible with the Plugin then we can go ahead and deactivate the Plugin, output a message, and halt the script.

Let’s check our Plugin is actually activated before we try to deactivate anything. We do this with the is_plugin_active() function. We need to pass in the Plugin folder and filename, which we stored in $plugin earlier. A value of true will be passed back if the Plugin is active.

Once we have confirmation that we can go ahead and deactivate our Plugin we just need to call the deactivate_plugins() function and pass it $plugin. This will actually deactivate the Plugin. The final step is to just call wp_die() with a suitable message. I have also added a link back to the WordPress admin for convenience.

You may be wondering why I am adding the code to a function and triggering it via the ‘admin_init’ action hook. Why not just add it outside of a function at the top of the Plugin file?

This is because of the is_plugin_active() function. If you try to call it outside of a function somewhere in your Plugin file, then it won’t have been defined by WordPress yet and a fatal ‘Call to undefined function’ error will be generated. This will also happen if you try to hook the function too early. Try replacing the ‘admin_init’ hook with ‘plugins_loaded’ instead to see what I mean. As long as you hook the function with ‘admin_init’ though everything should be fine.

The function is generic enough to be dropped into any existing Plugin and work right out of the box (neat huh?). The only thing you might need to adjust is the version of WordPress you want to test against.

I hope you find this code snippet useful. As usual let me know what you think in the comments.

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

Back to Basics: Domains, Hosting, DNS…How Does It All Work?

Ever wondered how website domains and hosting work? Do you need to change your DNS? Do you have your domain in one place and your hosting in another?

This video explains how it all works.

Read More

By

New Plugin – Format Media Titles

If you have ever uploaded many images/videos etc. via the WordPress media uploader you will now that it can be pretty tedious to have to manually edit the title for new media items.

‘Format Media Titles’ is a new Plugin to automatically format the media title for new uploads. It works by replacing characters such as hyphens, and underscores, with spaces. The title can then be capitalized by a method of your choice.

See the image below for a before and after view of the same image uploaded with and without the Plugin activated.

By

Better Theme Activation Handling

Here at Press Coders we are never happy with making do with the same old functionality. We constantly re-evaluate the way we do things and always look to improve on user experience. So, what have we been up to?

Well, one thing that bugs us is that when activating a theme for the first time your site can typically look less than amazing. That is until you create some content and complete some initial configuration including:

  • Posts
  • Pages (About Us, Contact Us, Sitemap etc.)
  • Navigation Menu (and setting the Theme Location)
  • Widgets and adding them to widget areas

Wouldn’t it be cool to be able to (optionally) install this content automatically when activating a theme on a new site?

Yes, we thought so too, and that’s why we added it to our theme framework! ;)

The actual code of creating the default content will be left to another post. In this post we want to focus on what happens on the theme activation side, and demonstrate how our framework makes it a snap to change this behavior when activating the theme.

Let’s see what a bog standard theme activation looks like.

OK, so here we have added an extra admin notice to show we have activated a theme, and even thrown in a link to the theme options page for good measure. But it still isn’t great.

For one thing, the default activation message feels a little outdated. I mean, what theme doesn’t support widgets these days? So let’s start by removing this default activation message. We are safe to do this because we know that all our current and future themes will ALWAYS support widgets.

How do we do this exactly? Well, we need to make sure our code runs when a theme is activated. There is no built-in WordPress hook for this (seriously) but we can use the following to achieve the same thing.

1
2
3
4
5
global $pagenow;
if ( is_admin() && isset($_GET['activated']) && $pagenow == "themes.php" ) {
	 /* Show theme activation message, and setup them option defaults. */
	add_action( 'admin_notices', array( &$this, 'theme_activated' ) );
}

We can add code to the ‘theme_activated’ callback function that will be executed every time a theme is activated. You may have noticed that this callback is referenced via class method syntax. This is because we are using classes rather than standard functions, thus the callback references need to be modified slightly.

Inside our callback function we have a line of jQuery code to remove the standard WordPress theme activation notice.

1
2
3
4
5
6
7
?>
<script type="text/javascript">
	jQuery(document).ready(function($) {
		$('#message2').css('display', 'none');
	});
</script>
<?php

Now that is gone we can add our own message when the theme is activated.

This is getting a little better now. We have a more relevant message with some buttons to go to the site home page, or theme options page.

But what about the default content mentioned earlier? Well, in the functions.php file we have two constants (INSTALL_DEFAULT_CONTENT, and INSTALL_CONTENT_PROMPT) that we can alter to change the activation message/behavior.

When INSTALL_DEFAULT_CONTENT is set to FALSE (the default setting) the above theme activation message is shown. But when it is set to TRUE we see a new activation message.

You can decide whether to install the default content or just go straight to the theme options page (or any other page you want to). To prevent accidental installation of default content the is an alert box that pops up to make sure you want to go ahead.

And if you do choose to install the default content, you get a confirmation message after completion.

The second constant, INSTALL_CONTENT_PROMPT, is only relevant if INSTALL_DEFAULT_CONTENT is set to TRUE. It is used to decide whether the default content to be installed should be installed automatically or prompt the user first.

We have already seen the effect of having INSTALL_CONTENT_PROMPT set to TRUE above where the default content is ONLY installed if the user specifies. If set to FALSE then the default content is installed silently in the background.

In this case the activation message is the same as before (see screenshot below) when INSTALL_DEFAULT_CONTENT was initially set to FALSE.

Why bother to install default content in the background without giving the user a choice? Well this option is pretty useful in situations where you ALWAYS want to make sure default content is installed every time a theme is activated. We already have one clear use in mind for this feature, for a proposed theme test area. Users will be able to sign up for an account and get full admin access to a blog where they can try out any of our themes.

In this scenario, it suddenly becomes clear that being able auto-install default content upon theme activation is pretty useful. This is a great way to show off a theme to its full potential right from the start, without the user having to do any initial configuration.

The theme activation feature discussed in this post is really still a work in progress, and the final implementation will almost certainly change before we use this in a production theme. But, we were pretty excited by this new addition to our theme framework, and wanted to share our development progress!

So let us know what you think in the comments. Would you find this feature useful?

By

Editing a WordPress theme’s CSS using Firebug (Video)

Learn how to make changes to your WordPress theme CSS using Firebug, a free Firefox browser add-on.

This video is an intro to Firebug, it is to help beginners make changes to WordPress themes.

Read More

By

Make a CSS3 button with an arrow using Pseudo-elements

Today I was working on a client site, and I wanted to make a button that looked like this:

CSS3 button with arrow

It’s a pretty typical iTunes style button except for the little triangle.

Since the site was in WordPress, I needed a flexible solution that would work with different button sizes, widths, text, etc.

There are several possible solutions for this, but I thought the best/easiest one was to use the :after Pseudo-element combined with the content property. This allows you to magically insert content (such as an image) and style it without adding anything to your HTML.

Here’s the good stuff.

HTML Markup

1
<a class="button" href="#">Learn More</a>

Clean and simple. Here’s the default CSS for the button without the triangle (not so simple, oh well):

Button CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.button {
	display: block;
	outline: none;
	cursor: pointer;
	text-align: center;
	text-decoration: none;
	font: bold 14px/100% "Trebuchet MS", Arial, Helvetica, sans-serif;
	overflow: hidden;
	padding: .4em 1em .5em 1em;
	margin: 10px 0;
	background: #3b88d8;
	background: -moz-linear-gradient(0% 100% 90deg, #377ad0, #52a8e8);
	background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#52a8e8), to(#377ad0));
	border-top: 1px solid #4081af;
	border-right: 1px solid #2e69a3;
	border-bottom: 1px solid #20559a;
	border-left: 1px solid #2e69a3;
	-moz-box-shadow: inset 0 1px 0 0 #72b9eb, 0 1px 2px 0 #b3b3b3;
	-webkit-box-shadow: inset 0 1px 0 0 #72b9eb, 0 1px 2px 0 #b3b3b3;
	box-shadow: inset 0 1px 0 0 #72b9eb, 0 1px 2px 0 #b3b3b3;
	color: #fff;
	text-shadow: 0 -1px 1px #3275bc;
	-webkit-background-clip: padding-box;
}

That gives you the blue button without the triangle. Here’s how we add the triangle with the :after Pseudo-element:

CSS for the triangle

1
2
3
4
5
6
7
.button:after {
        content: url(images/white-rt-triangle.png);
        width: 8px;
        height: 10px;
        float: right;
        margin: 1px 0 0 10px;
}

Pretty simple, you add the image with the content property, then you style it just like any other element. Boom! Triangle button domination.

The Whole Enchilada

Here’s the full CSS with :hover and :active states on the button:

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
.button {
	display: inline-block;
	outline: none;
	cursor: pointer;
	text-align: center;
	text-decoration: none;
	font: bold 14px/100% "Trebuchet MS", Arial, Helvetica, sans-serif;
	overflow: hidden;
	padding: .4em 1em .5em 1em;
	margin: 10px 0;
	background: #3b88d8;
	background: -moz-linear-gradient(0% 100% 90deg, #377ad0, #52a8e8);
	background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#52a8e8), to(#377ad0));
	border-top: 1px solid #4081af;
	border-right: 1px solid #2e69a3;
	border-bottom: 1px solid #20559a;
	border-left: 1px solid #2e69a3;
	-moz-box-shadow: inset 0 1px 0 0 #72b9eb, 0 1px 2px 0 #b3b3b3;
	-webkit-box-shadow: inset 0 1px 0 0 #72b9eb, 0 1px 2px 0 #b3b3b3;
	box-shadow: inset 0 1px 0 0 #72b9eb, 0 1px 2px 0 #b3b3b3;
	color: #fff;
	text-shadow: 0 -1px 1px #3275bc;
	-webkit-background-clip: padding-box;
}
 
.button:hover {
	background: #2a81d7;
	background: -moz-linear-gradient(0% 100% 90deg, #206bcb, #3e9ee5);
	background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#3e9ee5), to(#206bcb));
	border-top: 1px solid #2a73a6;
	border-right: 1px solid #165899;
	border-bottom: 1px solid #07428f;
	border-left: 1px solid #165899;
	-moz-box-shadow: inset 0 1px 0 0 #62b1e9;
	-webkit-box-shadow: inset 0 1px 0 0 #62b1e9;
	cursor: pointer;
	text-shadow: 0 -1px 1px #1d62ab;
	-webkit-background-clip: padding-box;
}
 
.button:active {
	background: #3282d3;
	border: 1px solid #154c8c;
	border-bottom: 1px solid #0e408e;
	-moz-box-shadow: inset 0 0 6px 3px #1657b5, 0 1px 0 0 #fff;
	-webkit-box-shadow: inset 0 0 6px 3px #1657b5, 0 1px 0 0 #fff;
	text-shadow: 0 -1px 1px #2361a4;
	-webkit-background-clip: padding-box;
}
 
.button:after {
        content: url(images/white-rt-triangle.png);
        width: 8px;
        height: 10px;
        float: right;
        margin: 1px 0 0 10px;
}

By

Testimonials WordPress Custom Post Type

Coming soon to a Press Coders theme near you… A Testimonial custom post type!

We created a testimonials WordPress custom post type to give us a ‘real world’ example to work with whilst we were experimenting with how these work inside of WordPress. It is our first attempt at using this awesome feature of WordPress, and it definitely won’t be our last. We have learned an awful lot the last few days tinkering around with custom post types, and custom taxonomies etc. It has been a real eye opener. It’s official, we have the custom post type bug now!

In fact, we already have another custom post type well under development that will make using content sliders in our themes an absolute dream! But more on that another time. Shhh… 😉

Click on the video below to see the testimonial custom post in action, and how all the features fit together, plus how the testimonial custom post types you create are actually used rendered on the front end of your site.

We have no firm plans to add the testimonial custom post type in our next theme, but with a little more polish it is going to find its way into one of themes sooner or later.

Let us know what you think, what custom post types you would love to see. The possibilities are endless. Inspire us, and we might just create a custom post type from your ideas!

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.

By

Create CSS Icons Using Pseudo-Classes and the Content Property

Displaying icons consistently across your website can be a mind-numbing task.

Using <img> tags is a terrible way to do it, and creating complex CSS with background images is a pain.

Enter the :before pseudo-class. The :before pseudo-class combined with the content property is great for displaying icons like this:

PDF Download
MP3 Download

Or like this:

Title With Icon

A Smaller Title With Icon

Pseudo-classes have been around since CSS1 way back in 1996. The great part about the :before class is that it is supported in all major browsers, IE included! (Just make sure you declare a !DOCTYPE or it won’t work in IE8.)

Getting Started

Step One

Get some icons and upload a few to your images folder. Between 22px and 32px square should work best, depending on your application.

Step Two

Create your html:

<a class="icon pdficon">PDF Download</a>

Using two different classes allows you to write less CSS if you are reusing this across your site.

Step Three

Add your CSS. We’ll apply the global styles using the .icon class, and display the image using the a.pdficon:before class.

You’ll notice the blue box included in the .icon code, you can ignore this if you want. The important part is in the a.pdficon:before styles.

.icon {
display: block;
padding: 5px 8px;
background: #e6effa;
border: 1px solid #bdd0e8;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}

.icon:hover {
background: #f4f8fd;
}

a.pdficon:before {
content: url(images/pdf-22.png);
display: block;
float: left;
margin-right: 5px;
position: relative;
bottom: 2px;
}

That’s it! Just change the a.pdficon:before class to something else to display a different image. For example, the code for the MP3 download above is:

a.mp3icon:before {
content: url(images/itunes.png);
display: block;
float: left;
margin-right: 5px;
position: relative;
bottom: 2px;
}

Notice the relative positioning – this is not always necessary, it just depends on how your icon is lining up.

Titles with Icons

The titles are the same concept, just slightly different code. Here’s the HTML from the larger title above:

<h2 class="widgeticon">Title With Icon</h2>

Here’s the CSS:

h2.widgeticon:before {
content: url(images/help-32.png);
display: block;
float: left;
margin-right: 5px;
}

Now go get cracking!