Archive for the ‘tuts’ Category

Perfect WordPress checkboxes

Friday, March 9th, 2012

I keep running into the same issue – dealing with checkboxes in custom meta boxes in WordPress. I’ve found a way to make these work for me. hopefully this can be of some use.

Here’s an example of the code that I was using:

// Add the Top and Featured News Meta Boxes ----------------------------------------//
add_action( 'add_meta_boxes', 'add_news_metaboxes' );

function add_news_metaboxes() {
add_meta_box('kdev_top_featured_news', 'Post status', 'kdev_top_featured_news', 'post', 'side', 'default');
}

// The Top and Featured Metabox
function kdev_top_featured_news(){
global $post;
$custom = get_post_custom($post->ID);
$kdev_meta_box_top = $custom["kdev_meta_box_top"][0];
$kdev_meta_box_feat = $custom["kdev_meta_box_feat"][0];
?>
<input type="checkbox" name="kdev_meta_box_top" <?php if( $kdev_meta_box_top == true ) { ?>checked="checked"<?php } ?> />  Top story?<br />
<input type="checkbox" name="kdev_meta_box_feat" <?php if( $kdev_meta_box_feat == true ) { ?>checked="checked"<?php } ?> />  Featured story?<?php
}

add_action('save_post', 'save_details');

function save_details($post_ID = 0) {
$post_ID = (int) $post_ID;
$post_type = get_post_type( $post_ID );
$post_status = get_post_status( $post_ID );

if ($post_type) {
update_post_meta($post_ID, "kdev_meta_box_top", $_POST["kdev_meta_box_top"]);
update_post_meta($post_ID, "kdev_meta_box_feat", $_POST["kdev_meta_box_feat"]);
}
return $post_ID;
}

The problem

I’ve used a few code snippets before for generating my custom meta boxes. The method above was working really well for me. At least it was, until I turned on wp_debug (which should always be on when developing!).

It turns out that this code generates a ‘notice’:

Notice: Undefined index: kdev_meta_box_top in path/to/functions/custom-meta-boxes.php on line 83

and if debug was on it would also generate:

Warning: Cannot modify header information – headers already sent by (output started at /path/to/wp-content/themes/mytheme/functions/custom-meta-boxes.php:83) in /path/to/wp-includes/pluggable.php on line 866

Line 83 of custom-meta-boxes.php contained this:


update_post_meta($post_ID, "kdev_meta_box_top", $_POST["kdev_meta_box_top"]);

Warning: Cannot modify header information” usually relates to extra whitespace at the start or end of your function files, but in this case I could see that the warning was coming from line 83 which wasn’t at the end. The notice and warning had to be related as they were both referencing the same line of the same file.

I still haven’t fully wrapped my head around the “Cannot modify header information” warning (help me out in the comments!), but I knew that if I stopped the notice, the warning would disappear.

The notice, “Undefined index” occurs when a variable has not been set. Basically, the function save_details() was referencing something that didn’t exist.

Why did it not exist? Because when the checkboxes were left unchecked, no variable was being set and passed to $_POST. So when the function asked for $_POST["kdev_meta_box_top"] (i.e. asked for the value of kdev_meta_box_top), that key didn’t even exist, never mind a value. Hence the notice.

The solution

I fiddled with various bits of logic to test for the value, etc. I realised that I needed to set a value for the checkbox, even if it wasn’t checked. That way kdev_meta_box_top would always have a value and the notice wouldn’t be generated.

Here’s my finished code:


// Add the Top and Featured News Meta Boxes ----------------------------------------//
add_action( 'add_meta_boxes', 'add_news_metaboxes' ); function add_news_metaboxes() {    add_meta_box('kdev_top_featured_news', 'Post status', 'kdev_top_featured_news', 'post', 'side', 'default');    }

// The Top and Featured Metabox
function kdev_top_featured_news(){
global $post;
$custom = get_post_custom($post-&gt;ID);
$kdev_meta_box_top = $custom["kdev_meta_box_top"][0];
$kdev_meta_box_feat = $custom["kdev_meta_box_feat"][0];

// We'll use this nonce field later on when saving.

wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' ); ?&gt;

&lt;input type="checkbox" name="kdev_meta_box_top" &lt;?php if( $kdev_meta_box_top != 'off' ) { ?&gt;checked="checked"&lt;?php } ?&gt; /&gt;  Top story?&lt;br /&gt;
&lt;input type="checkbox" name="kdev_meta_box_feat" &lt;?php if( $kdev_meta_box_feat != 'off' ) { ?&gt;checked="checked"&lt;?php } ?&gt; /&gt;  Featured story?&lt;?php}

add_action('save_post', 'save_details');

function save_details($post_ID = 0) {
$post_ID = (int) $post_ID;
$post_type = get_post_type( $post_ID );
$post_status = get_post_status( $post_ID );

// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
if(isset($_POST["kdev_meta_box_top"])) $kdev_meta_box_top = $_POST["kdev_meta_box_top"];
else $kdev_meta_box_top = 'off';
if(isset($_POST["kdev_meta_box_feat"])) $kdev_meta_box_feat = $_POST["kdev_meta_box_feat"];    else $kdev_meta_box_feat = 'off';

if ($post_type) {
update_post_meta($post_ID, "kdev_meta_box_top", $kdev_meta_box_top);
update_post_meta($post_ID, "kdev_meta_box_feat", $kdev_meta_box_feat);
}

return $post_ID;
}

I’ve added a nonce in there for validation too. Just to beef up the security! Let me know if it works for you.

Not perfect?

I doubt that this is actually the perfect solution. I’d love to hear some feedback about how this code can be improved. Please add your thoughts in the comments.

How to find your SSH key fingerprint on a Mac

Wednesday, March 7th, 2012

Open up your terminal and paste this in:


ls ~/.ssh/*.pub | xargs -L 1 ssh-keygen -l -f

It will return all your keys.

Custom Post Types

Saturday, November 19th, 2011

Last night I gave a presentation at the WordPress London meetup. I talked about custom post types in WordPress, something that has really excited me since WordPress 3. I’ve included the video, a rough transcript of the presentation and the slides at the bottom.

What we’ll cover

  • What are custom post types
  • When to use them
  • How to use custom post types
  • Taking things further
  • Resources

What are custom post types?

I’ve searched high and low on the internet for a decent definition of custom post types, with no luck. The best that I’ve seen is that they are really custom content types.

Replacing the word ‘posts’ with ‘content’ gives us a much better understanding of what custom post types are all about. The idea is that there is some content on your website that might not fit neatly into the typical page’ or ‘post’ mould. Think of the following examples:

  • Movies
  • Staff
  • Podcasts
  • Books
  • Products
  • Portfolio items
  • Testimonials, etc, etc.

Then why are they called custom post types?

Within WordPress there are already various post types: posts, pages, menus and revisions. With version 2.9 came the ability to define your own, ‘custom’, post type. These are stored in the wp_posts table. Hence custom post types.

When to use custom post types

Here is a fairly typical client request:

“I want to create a website for my holiday home rentals company. I have a portfolio of 20 properties that I want to be able to manage and update. Each property has the following information:

  • Name
  • Address
  • Short intro
  • Full property description
  • An image
  • Price per week
  • Number of rooms

I would like the user to able to sort the properties by ‘Price’ and ‘Number of rooms. I will also be blogging on the site.”

Without custom post types

In those dark days before WP 2.9 I probably would have used posts for the properties. I then would have created a category of ‘properties’ so that I could style those property posts differently than the regular blog posts. I then would have used custom fields for the meta data – rooms and price.

This used to work, but it was an ugly solution, a ‘hack’. The property posts would be mixed in with the regular blog posts both in the admin and the front-end.

Enter, custom post types

With custom post types we can separate our content into logical groups. Posts are now just chronological blog/news items again and properties have their own section.

This also makes theme development easier. The posts and properties are no longer lumped together, so no need to hack the index.php loop. New templates are available specifically for your properties post type too.

Basically, using custom post types is going to seriously improve workflow for both you and your client.

How to use custom post types

Creating your custom post type

Before I start, I have to tell you that there are ways to create custom post types on your WordPress site without having to touch a single line of code. There are several plugins and online code generators that will do it all for you. However, I strongly encourage you to have a go at this yourself. Even if this is the first bit of theme development that you have done, give it a go. You’ll have a much better idea of what’s going on and you’ll find it so satisfying.

Open up your theme’s functions.php file using your favourite text editor, and add the following:


add_action( 'init', 'create_my_post_types' );

function create_my_post_types() {
	register_post_type( 'kdev_properties',
		array(
			'labels' => array(
				'name' => __( 'Properties' ),
				'singular_name' => __( 'Property' )
			),
			'public' => true,
			'has_archive' => true,
            'supports' => array('title','editor','excerpt','thumbnail'),
            'rewrite' => array( 'slug' => 'property' ),
            'register_meta_box_cb' => 'add_property_metaboxes',

		)
	);
}

This code is all we need to get custom post types working on our WordPress site. in fact, it’s more than we need, I’ve added a few lines, 11, 13 and 14, that aren’t essential but useful for what we’re trying to achieve.

Line 4 is where the magic starts, we’re registering our post type and giving it a name. I’ve prefixed the name with ‘kdev_’ to avoid clashes with any other plugins.

Line 6 starts the ‘labels’ array and at this point we’re only using two labels ‘name’ and ‘singular_name’. These will appear in our theme instead of the ugly ‘kdev_properties’. There are lots more labelling options, check them out here http://codex.wordpress.org/Function_Reference/register_post_type#Arguments.

Line 10 is telling WordPress to make the post type public, that is visible, in the admin and front-end. Strangely this defaults to false, so you must include it if you want to see your post type.

‘has_archive’ on line 11 is optional. I’m using it to tell WordPress that I will be using a custom archive template.

The ‘supports’ array on line 12 is where it starts to get interesting. Everything that you are familiar with from posts and pages are available to you here. I’m just enabling the elements that we’ll need for our property post type.

Line 13 enables a URL rewrite. This changes our URL structure from kdev_properties/propertyname to property/propertyname (assuming we’re using a ‘pretty’ permalink structure).

The last line, 14, is telling WordPress that I wish to use a custom meta box on this post type. this will be explained in greater detail later on.

Now log in to your WordPress admin area and you should see something similar to the following:

You can see that our custom post type, ‘properties’, has been added to the main menu, keeping it separate from posts and pages.

If you click on the ‘Properties’ link and then ‘Add New’ you will get to the following screen.

Here we can see the ‘supports’ array in action. We’ve added some useful functionality here but it’s also important to note what we’ve left out. The categories and tags that we are familiar with from posts are gone, as are page attributes, revisions, comments and discussions. This leaves us with a nice clean UI. There are no extraneous admin elements to distract the user.

Our code hasn’t just created a great admin screen, it’s also enabled us to view our custom post type live on the site. From the ‘Edit Post’ screen, click on ‘Preview’ to see what your post will look like (add some content first for a better effect!). You’ll see something like this:

That’s great so far, but the chances are that you’ll want your custom post type to look slightly different to regular posts. WordPress gives us two template files to do this; single-[posttype].php and archive-[posttype].php.

The single template will let you style your individual custom post types, in our case the single property page. It’s often easiest just to create the new template file (e.g. single-kdev_properties.php), in your theme directory, and copy and paste the code from your theme’s single.php file. Then you can make any changes that you require. Before you do that though, there are some more tricks that will help you make your custom post type really come to life!

The archive-[posttype].php template will create a page that displays a list of your custom posts. Using the same idea as above, you can copy and paste from your index.php file and edit from there. Remember the ‘has_archive’ argument that we added? That line is telling WordPress to use our custom archive file.

Congratulations! You’ve created your first custom post type. That wasn’t too hard was it? There is loads more that we can do with our custom post type.

Taking things further

Remember the original client request? She wanted to be able to add ‘price’ and ‘number of rooms’ data to her properties. Of course, we could just add this to the main text editor, but then it would be tricky to separate the data if we wanted to use it by itself. This is where custom meta boxes come in.

Custom meta boxes

Here’s where custom post types start to get really cool. We’re not limited to the ‘title’, ‘excerpt’, etc. that WordPress provides us with. We can add new boxes to our edit screen that accept any kind of data that we can think of.

Here’s an example of some meta boxes:

The first meta box is a simple text field, the second a radio button. You could have checkboxes, text-areas, TinyMCEs, etc. By now your imagination should be kicking in to show you the possibilities available!

We want two meta boxes, one for price and one for rooms. Here’s the code that we need to achieve this:


//Add custom meta box

// Add the Properties Meta Boxes

function add_property_metaboxes() {
    add_meta_box('kdev_properties_rooms', 'Number of Rooms', 'kdev_properties_rooms', 'kdev_properties', 'side', 'default');
    add_meta_box('kdev_properties_price', 'Price per week', 'kdev_properties_price', 'kdev_properties', 'side', 'default');
}

// Output the Property metaboxes

function kdev_properties_rooms() {
    global $post;

    $prop_rooms = get_post_meta($post->ID, '_rooms', true);

    echo '<label>Rooms</label><input class="widefat" name="_rooms" type="text" value="' . $prop_rooms  . '" />';
}

function kdev_properties_price() {
    global $post;

    $prop_price = get_post_meta($post->ID, '_price', true);

    echo '<label>Price per week</label><input class="widefat" name="_price" type="text" value="' . $prop_price  . '" />';
}

// Save the Metabox Data

function kdev_save_property_meta($post_id, $post) {
    if ( 'kdev_properties' == get_post_type() ) {

        if ( !current_user_can( 'edit_post' , $post ->ID )) return $post ->ID;

        $property_meta['_rooms'] = $_POST['_rooms'];
        $property_meta['_price'] = $_POST['_price'];

        foreach ($property_meta as $key => $value) { // Cycle through the $property_meta array!
            if( $post->post_type == 'revision' ) return; // Don't store custom data twice
            $value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
            if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
                update_post_meta($post->ID, $key, $value);
            } else { // If the custom field doesn't have a value
                add_post_meta($post->ID, $key, $value);
            }
            if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
        }
    }
}

add_action('save_post', 'kdev_save_property_meta', 1, 2); // save the custom fields

This is a bit more complex and I won’t go through every line. Add this to your functions.php file and make sure that the variable names are correct (if you have used something other than ‘kdev_properties you’ll need to change it here too).

There are some arguments that you may wish to tinker with. Remember, you won’t learn if you don’t make mistakes, so don’t be scared. It’s always a good idea to make backups before you start experimenting though, especially with a live site.

Adding that code will give you something like this:

Check out those custom meta boxes on the right! Sweet.

As cool as it is to have custom meta boxes, they’re not going to do anything for you without a bit of work to your template files.

Open up one of your custom template files and add the following:


Price per week: £<!--?php echo get_post_meta(get_the_ID(), '_price', true); ?-->

Number of rooms: <!--?php echo get_post_meta(get_the_ID(), '_rooms', true); ?-->

The get_post_meta() function is creating all the magic here. It takes a few arguments, the post ID, the meta key, and whether to return a single string or an array (‘true’ will return the string).

I’ve added those lines to my custom archive template to get the following:

Nice work. Our custom post types have meta boxes and we have some pretty nifty templates. There’s one more part to the holy trinity of custom awesomeness…

Custom taxonomies

Taxonomies are ways to classify your data. If you’re familiar with WordPress you will already be using them; categories and tags. These are both taxonomies, but they are very general, and you’ll probably want to keep these for your blog posts.

For our custom post types we can create our own custom taxonomies. There are two main types; hierarchical and, erm, not.

Hierarchical taxonomies

Hierarchical taxonomies have the concept of parents and children, like categories. You can create tree like structures of nested classifications.

Non-hierarchical taxonomies

These are like post tags. They don’t have parents or children.

Creating a custom taxonomy

function my_register_taxonomies() {

	register_taxonomy(
		'area',
		array( 'kdev_properties' ),
		array(
			'public' => true,
			'labels' => array( 'name' => 'Area', 'singular_name' => 'Area' ),
			'hierarchical' => true,
		)
	);
}

add_action( 'init', 'my_register_taxonomies' );

This is all we need to create a custom taxonomy for our custom post type. I’ve given it a name, assigned it to the ‘kdev_properties’ post type and given it some arguments. Again, have a play around. The code can be added to your functions.php file as before.

And so we have it. Well done for getting to the end!

Hopefully, you’ll be inspired to use custom post types on your next project. You’ll never look back, I promise.

Resources

http://codex.wordpress.org/Post_Types

http://codex.wordpress.org/Function_Reference/register_post_type

Plugins

http://wordpress.org/extend/plugins/custom-post-type-ui/

http://wordpress.org/extend/plugins/custom-content-type-manager/

Posts

http://justintadlock.com/archives/2010/04/29/custom-post-types-in-wordpress

http://devpress.com/blog/conditional-checks-for-custom-post-types/

http://css-tricks.com/forums/discussion/8538/wordpress-3.0-custom-post-types-and-meta-boxes/

Easy meta boxes with WPAlchemy

http://www.farinspace.com/wpalchemy-metabox/

The slides


Proper float clearing

Monday, June 6th, 2011

I was browsing through Forrst recently and happened across the following advice on float clearing.

An easy way to properly clear floats without extra markup. If you’re not using some sort of clearfix you probably should be.

.clearself:before,
.clearself:after {
content: " ";
display: block;
height: 0;
overflow: hidden;
}
.clearself:after {clear: both;}
.clearself {zoom: 1;} /* IE < 8 */

This looks like a great way of reducing design related markup in your HTML. What do you think? Have you tried this technique before?

The original post is here.

HTML Fractions

Tuesday, April 19th, 2011

I wanted to use some pretty fractions in an article today. I don’t like the look of “1 1/2″, not very elegant.

Of course, the answer lies within HTML special characters. There are a few ways to achieve the same thing:

  • &frac14; will give you ¼. You can change the ‘1’ and ‘4’ to any other number. But hang on, what would &frac124; give you? The answer is ½4;. Hmm…
  • The more versatile solution is to use &frasl;. However, this won’t format properly without adding <sub> and <sup> like:

    <sup>1</sup>&frasl;<sub>10</sub>

    Which will output 110.

Boom! HTML fractions!

Drop down menus, z-index and IE

Tuesday, April 19th, 2011

One of Internet Explorer’s (IE) most commonly encountered bug is when using z-index. I experienced this recently when using the DDSlider plugin for WordPress along with a drop down navigation.

Whilst doing some browser testing I noticed that the drop down menu hides behind the DDSlider. I tried to fix this using z-index. I applied positions and z-index to the offending elements but they still did not behave properly.

After Googling the issue I came across this post which explains the problem perfectly. I needed to apply z-indexes to higher level elements that sit side by side in the DOM. In my example I applied a position:relative; z-index:2 to the #header div and a position:relative; z-index:1 to the #main div. Seems to have done the trick perfectly!

Spinning Update progress on WordPress pages

Friday, April 15th, 2011

Spinning Progress Wheel

One of my clients recently informed me that a site that I had built had a problem; when some pages were published or updated, the progress wheel would spin until the browser eventually timed out.

It had been a month or so since I had finished the site development and there had been lots of new content and plugins added. I turned on the WordPress debugging and got to work.

Finding the problem

There were a lot of errors being generated, mostly from plugins but also from WP itself. I also noticed a few memory limit issues which I fixed using the .htaccess file.

I got to work isolating the various components. All plugins, themes and content were tested to no avail. Next up I installed the site on different servers. I looked at the database for anomalies, contacted the hosting provider, nothing.

Lying in bed last night I couldn’t sleep, I had to give it another go. I did some more tests on what I thought was the offending plugin and associated database table. Still no joy. In one last ditch attempt I did various Google searches of the symptoms. I jumped from forum to forum and followed links all over the place.

Got it!

Then I found it. The custom permalink structure of “/%category%/%postname%/” that I have used on nearly every site was the culprit. Now, someone please correct me if I’m wrong, but I’m sure the WordPress codex used to give that exact structure as an example of how to implement “Pretty Permalinks”. Not any longer. Apparently that structure causes performance issues on sites with lots of pages. For every page a whole new set of rewrite rules are created until the system just can’t process it any more.

The solution is to use a non-verbose entry at the start. For example %year% or %month% or both are ideal but %category%, %postname%, %tag% and %author% should be avoided.

Fortunately, the codex has been updated to advise against this practice and the new example “pretty permalink” is /%year%/%postname%/.

Lessons learned

For most site you can probably get away with the offending structure. In fact many SEO and WordPress ‘gurus’ recommend it. Just be warned that if your site grows in terms of pages then you may encounter this problem in the future.

Some of the lessons that I’ll take with me:

  • Keep up to date with changes to WordPress documentation and best practices.
  • Clearly define who takes responsibility for WordPress faults in your project contract.
  • Never give up!

Internal Link Layout Issue

Thursday, January 27th, 2011

I recently came across an unusual problem when using internal links on a WordPress site. The link in question linked from one page on the site to a specific section on another page of the same site. When this link was followed there was an error with the page layout. More accurately, the new page layout was technically correct and the rest of the site was wrong.

I struggled for a while trying to find the source of this problem. I looked at the ‘error’ page in firebug and compared it to a normal page on the site. On all other pages there was a mysterious magin (or padding) created at the top of a div but when this page was visited from the link the margin/padding disappeared.

Long story short, the div in question was set to overflow:hidden. When I commented out that line, the problem resolved itself. Why? I don’t know. Can anyone shed any light on this?

Custom Post Type Archive Pages – WordPress

Wednesday, January 12th, 2011

Need to show your custom post types on your category archive pages?

Add this to your functions.php file:

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
  if(is_category() || is_tag()) {
    $post_type = get_query_var('post_type');
	if($post_type)
	    $post_type = $post_type;
	else
	    $post_type = array('post','cpt'); // replace cpt to your custom post type
    $query->set('post_type',$post_type);
	return $query;
    }
}

Now change the variable ‘cpt’ to the registered name of your custom post type, and voila!

A big thanks to parandroid over at http://wordpress.org/support/topic/custom-post-type-tagscategories-archive-page?replies=16 for this one.

WordPress Custom Post Templates

Friday, January 7th, 2011

Once you have built a Wordpres custom post, you will often wnat to style it using it’s own template.

I searhed the web for a solution and courtesy of twothirdsdesign, if found the answer.

The template used for a custom post view is decided by the ‘get_single_template()’ function in the wp-includes/theme.php file.  And it basically tells locate_template() to look for single-’post_type’.php or single.php.

So the simplest way to customise the way a custom post is displayed is to add a template file to your theme with the name single-xxxxxx.php

Simples!