So I got this video from a friend, and I wanted to post it on my site, but I wanted to do it without using any Flash, or any plugins, and I wanted it to work on the iPhone, and Chrome, and Firefox, and IE…

Step 1: Convert the file.

First I took the file and used Miro Video Converter to make two versions of the file. The first version I made was using the “Theora” format. This is an Ogg format, and you basically only need to make it for the video to show up in Firefox. Future versions of Firefox will support the WebM format instead (Chrome supports it now), so when Firefox 4 comes out, use that format.

Next, use Miro again and this time make a version using the iPhone preset. This basically creates an MP4 version of the file, but at the right resolution to have it show up on the iPhone. Annoyingly, the original file was from an iPhone, so it should have played, but it wouldn’t on mine. I suspect that the resolution difference between the iPhone 4 (used to make the video) and the iPhone 3GS (which I have) is the problem. Regardless, I just used the preset to downscale the video resolution.

Step 2: Adjust WordPress’ settings

WordPress didn’t like me uploading these files. Turned out that it was because I’m on multisite. In the Network Admin screen, find the Network Settings menu option, go to the bottom of the page, and add the mp4 and ogv extensions to the list of allowed files. Also add webm while you’re there, for the future.

Note: If you’re not on multisite but still have problems uploading the files, then add this line of code to your wp-config.php file, to turn on the unfiltered_upload capabilities for administrators:

define('ALLOW_UNFILTERED_UPLOADS',true);

Step 3: Check .htaccess settings

One of the things WordPress relies on to know if it’s a video or not is the MIME Type. Some servers have these properly configured, some don’t. Doesn’t hurt to help the process along by explicitly defining some of them in the .htaccess file. For good measure, I added a bunch of common ones, just to be sure:

AddType text/xml .xml
AddType video/mp4 .mp4 .m4v
AddType video/mpeg .mpeg .mpg
AddType video/quicktime .mov
AddType video/ogg .ogv
AddType video/webm .webm
AddType audio/mp4 .m4a .m4b .m4r
AddType audio/mpeg .mp3
AddType audio/playlist .m3u
AddType audio/x-scpls .pls
AddType audio/ogg .ogg
AddType audio/wav .wav

Step 4: Upload the videos

Easy one. Go into the Media->Library and upload your two videos. After doing that, get the URLs of both of them.

Step 5: Make the post

Make a new post and type in everything you want to type in. Then make sure you’re in the HTML editing mode, and add this code to the post:

<video width="640" height="360" controls>
  <source src="http://example.com/wp-content/uploads/video.mp4" type='video/mp4'></source>
  <source src="http://example.com/wp-content/uploads/video.ogv" type='video/ogg'></source>
</video>

There’s a few things there you’ll need to manually edit.

Obviously the URLs need to point to your files. Also, it’s important that the MP4 one is first, some older iPad software doesn’t like it otherwise.

The second one is the width and height. Now, like with posting images, these don’t have to exactly match the actual width and height of the video. The browser will use these sizes and scale the video accordingly. However, you’ll want to get the aspect ratio correct, so you don’t stretch or squish the video into the wrong sized box. And you can leave the height and width out entirely to not scale it, if you got your sizes correct in the video itself. But it’s a good idea to have them there regardless, to clue the browser into the size beforehand and speed up page rendering. Also note that the iPhone doesn’t care about those width and height tags, since it will just show the video full screen when you tap on it.

Sidenote: Do NOT switch into Visual mode. TinyMCE will muck up this code, badly, and try to add a SWF player to it and Flash and a bunch of other stuff. This is probably by design, but I wanted to do this without Flash at all and see how that worked. Turns out to work fine in the browsers I tested.

Finally, preview and publish as normal.

Wantlist

One thing I haven’t figured out is how to target the iPhone specifically with a separate file. With this setup, Chrome and IE are now showing the iPhone file, which is lower resolution than the OGV file (which is at original resolution). In this specific case, the video was poor and so it doesn’t make much difference, but I’d prefer to have a separate file specified that only iPhones used without having to resort to user agent targeting.

EDIT: Turns out you can do this with a media query on the source that targets the iPhone. So here’s my new code:

<video width="640" height="360" controls>
  <source src="http://example.com/wp-content/uploads/video.iphone.mp4" type='video/mp4' media='only screen and (max-device-width: 480px)'></source>
  <source src="http://example.com/wp-content/uploads/video.mp4" type='video/mp4'></source>
  <source src="http://example.com/wp-content/uploads/video.ogv" type='video/ogg'></source>
</video>

The media attribute lets you specify a CSS3 Media Query. The max-device-width of 480px = iPhone. So desktop browsers will use the video.mp4 while the iPhone uses the video.iphone.mp4. I’ve confirmed that this works properly with Chrome.

It’s interesting to see that browsers can do this reasonably well, even if you do have to make a few different versions of the video.

Shortcode Plugin

At the suggestion of ipstenu in the comments below, I made this into a shortcode plugin. You can download it here:
HTML5 Video Shortcode.

This plugin has the advantage of being ignored by TinyMCE. :)

Shortlink:

Was trying to upload some photos and noticed that the captions I had set on the photos in Picasa showed up as titles in WordPress instead of as captions. Examining the core code, I found that it’s a known issue, but that fixing it in the core isn’t so easy, since WordPress has to support a number of different image editing programs and such. Different programs use the EXIF fields in different ways.

But I mostly use Picasa for photo management, so I don’t care about those other programs. So I wrote a quick plugin to fix the problem with WordPress and Picasa photos. Basically it just rejiggers the attachment when it’s added (but not when it’s edited) and puts the caption in the right place.

<?php
/**
Plugin Name: Picasa Captioner
Description: Fix up WordPress to read Picasa Captions from EXIF info properly.
Author: Otto
Author URI: http://ottodestruct.com/
**/

add_filter( 'wp_read_image_metadata', 'picasa_adjust_caption' );
function picasa_adjust_caption($meta) {
	if (empty($meta['caption']) && !empty($meta['title'])) {
		$meta['caption'] = $meta['title'];
		$meta['title'] = '';
	}
	return $meta;
}

add_action( 'add_attachment', 'picasa_adjust_attachment' );
function picasa_adjust_attachment($id) {
	$attachment = & get_post( $id, ARRAY_A );
	if ( !empty( $attachment ) ) {
		$attachment['post_excerpt'] = $attachment['post_content'];
		$attachment['post_content'] = '';
		wp_update_post($attachment);
	}
}
Shortlink:

While looking at my backlinks today, I noticed a site in French had linked to my post about making photo galleries. He mentioned that the Google Translate wasn’t great. I took a look, and while I don’t know how good the text translation was, I did notice that Google strangely tried to translate the code as well, thus screwing it all up.

A quick search revealed that all one had to do was to add the “notranslate” class to any wrapping object to prevent its contents from being translated.

Now, I use the Syntax Highligher Evolved plugin to display code on my site (although I use an older version because I like the look and functionality of it better than the latest version). So I edited the plugin and found where it inserts the PRE tag, and added the notranslate class to it.¬†And voila, now my code doesn’t get translated anymore.

Just a helpful tip for anybody who posts code on their sites.

Shortlink:

Google rolled out their +1 button today. So I added it here. You’ll find it below all the posts. Try it out.

Here’s the simple-stupid plugin I wrote to do it. While you can just edit your theme, I like making these sort of things into plugins. That way, I can turn them off at will, and I know exactly where to go to change them without having to dive into my theme code. Also, if I change themes, the code still works on the new theme.

<?php 
/* 
Plugin Name: Otto's Google +1 Button
Description: Add a +1 button after the content.
Author: Otto
Version: 999
*/

add_filter('the_content', 'google_plusone');

function google_plusone($content) {
	$content = $content.'<div class="plusone"><g:plusone size="tall" href="'.get_permalink().'"></g:plusone></div>';
	return $content;
}

add_action ('wp_enqueue_scripts','google_plusone_script');

function google_plusone_script() {
	wp_enqueue_script('google-plusone', 'https://apis.google.com/js/plusone.js', array(), null);
}

I wrapped the button in a div so that I could style it. In my particular case, I’m floating it right and giving it a margin, same as the Twitter and Facebook plugins. One day, I’ll make all these little Google plugins more generic and configurable, and roll them into a Simple Google Connect plugin. :)

One thing I don’t like is that the +1 button only works for people who are logged into a GMail account. Sorry Google Apps users, you’re out of luck. Complain to Google until they fix it.

If you want to add more parameters to the plugin and reconfigure it, you can find out about the available parameters here: http://code.google.com/apis/+1button/#configuration

Shortlink:

Just upgraded to the beta of 3.2. I like the new admin interface overall. Really, I do. But relatively minor things tend to bug me sometimes.

For example, I don’t much care for the Site Title being so tiny and hidden at the top of the admin screens. I like the site’s name to be big and prominent, as it’s a link to the front end of the site. On multi-site, it’s awfully nice to see at a glance what site I’m on. I often click that link to go to the front end of the site easily. So trying to navigate to the front end became difficult and hit or miss with this title being so tiny.

I also don’t like seeing the Page Title being so big and having a big ol’ icon there beside it. The Page Title strikes me as kinda useless. I mean, I know what screen I’m on.

So I wrote a quick tweak plugin to fix it. I’m posting it in case it bugs you as much as it bugs me. On a side note, it’s a quick little demo of how to modify the WordPress admin CSS quickly and easily.

<?php 
/* 
Plugin Name: Embiggen Site Title for WordPress 3.2 beta
Description: Embiggen the Site Title in wp-admin. Debiggen the Page headers. Ditch the useless icon.
*/
add_action('admin_print_styles', 'big_site_title');
function big_site_title() {
?>
<style>
.wp-admin #wphead {
	height: 42px;
}
.wp-admin #wphead h1 {
	font-size: 28px;
	#font-family: "HelveticaNeue-Light","Helvetica Neue Light","Helvetica Neue",Helvetica,Arial,sans-serif; #uncomment this if you want to go to the sans-serif font
}
.wp-admin #header-logo {
	background-image: url("images/logo.gif");
	background-size:32px 32px;
	width:32px;
	height:32px;
}
.wp-admin .wrap h2 {
	font-size:16px;
	padding-top: 1px;
	padding-bottom: 0px;
	height:20px;
}
.wp-admin .icon32 {
	display:none;
}
</style>
<?php
}

Feel free to tweak further as desired. Also, WordPress might change further before 3.2 is released, so this may stop working or need further tweaking.

Shortlink:

I have seen many questions from people about how to create photo galleries in WordPress. But often I see these questions answered by somebody recommending a plugin or something like that. You don’t really need plugins to create photo galleries. WordPress has a huge amount of gallery functionality built right in. You just need to make your theme smarter in order to take advantage of it.

Note: Matt has one of the neatest photo gallery implementations around, and he often gets questions about it. So I’m going to refer to it from time to time in this post. Maybe you’ll want to head over there and familiarize yourself with some of the look and features of it.

Understanding the Gallery Concept

One of the first things you need to know is how WordPress organizes Galleries. A gallery is really just a post with a bunch of images attached to it.

While editing a post or creating a new one, you have the option to upload images or other files. When you upload a file through the file Uploader, WordPress creates a post just for that file. This post has a post_type of “attachment”. Images in particular get some extra processing, and they show up in multiple sizes, you can insert them into the posts, etc. You probably already knew that. You probably have seen the gallery inserter, which just inserts the “gallery” shortcode into your post.

What you might not have known is that it’s doing more than you think. It’s not just resizing those images you’re uploading, but it’s pulling out metadata and other information about the image too. It’s grabbing alot of the EXIF data from the image and storing it as postmeta items for that attachment post. The post itself, being a post, gets its own URL, which is the post that it is attached to’s URL followed by the attachment posts title. Basically, an attachment post is sorta like a child of the parent post, which contains the gallery. So all a gallery really is is the sum of the attachments posts that are children of the gallery post itself.

Graph of the Gallery concept

Is that clear as mud? Don’t worry, it’s simpler to work with than you think.

Create an Image Template

First thing you need to do is to edit your theme (or create a child theme, if you prefer). What you’re going to do is to make an “image.php” file.

(Side note: If you browse through the source of WordPress, you’ll never find where it loads the “image.php” file, because it isn’t there. What it is actually doing is looking for the mimetype of the attachment as a filename. So since you uploaded, say, a JPG file, then the mimetype is image/jpeg. It splits that and looks for image.php, followed by jpeg.php, followed by image_jpeg.php, and finally just attachment.php as the generic base. It does this for any and all attachments, and any and all mime types. So you can have a video.php for video attachments, audio.php for audio attachments, etc.)

The image.php file is the template that will load for “single images”. A gallery shows thumbnails, but when you click on them, you go to the attachment page for just that image. An easy way to start with your custom image page is to copy your existing single post page to it. Just copy single.php to image.php. If you don’t have a single.php, maybe you should try copying the index.php file instead.

Modify your Image Template

Since this is an image, it’s going to have things in it that normal posts don’t. It’s also going to need special navigational entries that other posts don’t have.

For starters, it has a parent, which is the post containing the gallery. So what if we want to display the gallery post’s name? Easy, we can reference the parent using $post->post_parent. So code like get_the_title($post->post_parent) will get us that title so we can echo it. Similarly, using something like get_permalink($post->post_parent) will get us the link back to the gallery. So this sort of code in our image template will display that link:

echo "<a href='" . get_permalink($post->post_parent). "'>Go back to ". get_the_title($post->post_parent) ."</a>";

For navigation, we have special functions. previous_image_link and next_image_link will let us display links to the previous or next images in the gallery order. Each of these takes two parameters. The first is the size of the previous or next image we want to display (or false to not show a thumbnail at all), the second optional parameter is some text to put in the link. So to show a couple of text navigational links, this code would work:

echo previous_image_link(false,'Previous Photo');
echo next_image_link(false,'Next Photo');

If I wanted to display image links instead, I could change that false to ‘thumbnail’ to display the thumbnail sized images. Or ‘medium’. Or whatever size I preferred.

Next we want to display the image. The wp_get_attachment_image function takes care of that easily:

echo wp_get_attachment_image( $post->ID, 'medium' );

The second parameter there is the size we want to display it at. You could also use ‘large’, ‘full’, ‘thumbnail’, etc. Any of the image sizes. If you want the image to be clickable, you might wrap it in an A tag and link it to the image itself.

But remember that attachment posts are still posts. All those fields you can enter on the image uploader are available to you to use. For example, the “Title” is stored in the normal Post Title field, so calling the_title() will display that. The Description is stored in the Content field and can be displayed with the_content(). The Caption is stored in the Excerpt field and can be displayed with the_excerpt(). You should use these as needed.

EXIF Information

Here’s an example of one of Matt’s single image pages, showing a balloon: http://ma.tt/2011/05/balloon-ride/mcm_9033/.

Nice shot. Scroll down a bit and look on the right hand side of that page, where it says INFO. Lots of nifty information there. But he didn’t put any of that in, WordPress did it all by itself.

To gain access to that information in your image.php file, you use this code:

$imagemeta = wp_get_attachment_metadata();

If you examine this array, you find that it contains widths, heights, filenames of the various sizes of thumbnails generated, etc. But it also contains an array called “image_meta”. This is an array of information that represents everything WordPress was able to glean from the image itself. After you know this, it’s just a matter of displaying it properly.

For example, to display the camera name, he has code similar to this:

if ($imagemeta['image_meta']['camera']) {
	echo "Camera: " . $imagemeta['image_meta']['camera'];
}

There’s other bits in there, like Aperture, Focal Length, ISO settings, and Shutter Speed. Most of these are straightforward, except for shutter speed which is often not in an easy format to display. Usually it’s a fractional value, represented as a decimal. Often we want to convert this to the fractional display. Here’s a bit of code I wrote to do that. It’s not perfect, but what is?

if ($imagemeta['image_meta']['shutter_speed']) {
	echo 'Shutter: ';

	// shutter speed handler
	if ((1 / $imagemeta['image_meta']['shutter_speed']) > 1) {
	echo "1/";
		if (number_format((1 / $imagemeta['image_meta']['shutter_speed']), 1) ==  number_format((1 / $imagemeta['image_meta']['shutter_speed']), 0)) {
			echo number_format((1 / $imagemeta['image_meta']['shutter_speed']), 0, '.', '') . ' sec';
		} else {
			echo number_format((1 / $imagemeta['image_meta']['shutter_speed']), 1, '.', '') . ' sec';
		}
	} else {
		echo $imagemeta['image_meta']['shutter_speed'].' sec';
	}
}

Ugly, I know, but it gets the job done, more or less. Works on most shutter speeds I’ve tested it with.

Gallery Formatting in the Stream

Now, obviously you want your posts to look good in the normal flow of the blog as well. Twenty-Ten and the upcoming Twenty-Eleven themes both show you how to do this rather easily. Twenty-Ten used the “gallery” category for this at one point, before Post Formats came along and made that method obsolete. Now it uses the gallery post format instead.

So first, obviously, your theme will need to support the gallery post format. This is easy, just add this to your theme’s functions.php if it doesn’t have gallery support already (or add “gallery” to it if it does have post format support).

add_theme_support( 'post-formats', array( 'gallery') );

Now that that’s done, you have the option of choosing gallery as a post format. So you need to edit your theme to use that flag as an indicator to display things differently.

There’s plenty of tutorials on post formats out there, so I’ll assume you’re more than capable of figuring out how to use has_post_format(‘gallery’) or the “.home .format-gallery” CSS indicators to style the posts as needed.

What you need to know for specific gallery formatting in the main stream of the blog is how to display a selected representative image from the gallery there instead of the whole thing. There’s two basic steps to this.

First, you have to write your post appropriately to begin with. Take one of Matt’s posts for example: http://ma.tt/2011/05/20/

Here’s how that post actually looks in the editor:

Description text at the top here... Went for balloon ride, etc.
< !--more-- >
[ gallery ]

In other words, he puts the description first, then the more tag, then the gallery after it. This has the effect of giving a natural separation of the description content and the gallery itself. The gallery is not displayed on the front page, because it’s after the more tag. So a call to the_content() on the stream pages will only show the description.

Secondly, you can easily adapt the Featured Image function to let you choose which image to display in the stream. All the user has to do is to upload their gallery then select one and set it to be the featured image. Voila, it’ll be the main representative one used.

if ( has_post_thumbnail() ) {
        // use the thumbnail ("featured image")
        $thumb_id = get_post_thumbnail_id();
	the_post_thumbnail( $size ); // whatever size you want
}

By tossing a div around that, you can then float it left, or right, or whatever you prefer to do. With some extra code and the use of the get_children function, you can make this default to the first image in the gallery if they don’t choose a featured image.

else {
	$attachments = get_children( array(
		'post_parent' => get_the_ID(),
		'post_status' => 'inherit',
		'post_type' => 'attachment',
		'post_mime_type' => 'image',
		'order' => 'ASC',
		'orderby' => 'menu_order ID',
		'numberposts' => 1)
	);
	foreach ( $attachments as $thumb_id => $attachment )
		echo wp_get_attachment_image($thumb_id, $size); // whatever size you want
	}
}

Using tricks like this, you can get the bits of the gallery yourself and display them in different ways.

Make a Gallery Specific Page Template

Matt’s Gallery Page is itself customized. It displays the galleries in an entirely different way. There’s a big copy of the featured image, along with a few thumbnails below the description, and it even has a count of the images in each “album”. This is all done with a pretty straightforward page template.

So to start, make a Page Template:

/*
Template Name: Gallery
*/

Right at the top of the template, we’re going to add a special taxonomy query, which will get all the gallery posts (as well those in the gallery category, since we’re being backward compatible and all). So here’s the code:

$args = wp_parse_args($query_string);

query_posts(array(
         'tax_query' => array(
                'relation' => 'OR',
                array(
                        'taxonomy' => 'post_format',
                        'terms' => array('post-format-gallery'),
                        'field' => 'slug',
                ),
                array(
                        'taxonomy' => 'category',
                        'terms' => array('gallery'),
                        'field' => 'slug',
                ),
        ),
        'paged' => $args['paged'],
) );

First we parse the normal arguments, then we override them with our own query. The only argument we really use from the normal set is the page number, for multiple paging.

Our overriden query uses an advanced taxonomy query. In this case, it selects any posts in the gallery post format, or any post with a category of gallery. By passing this to query_posts, we override our main page query, and thus our main Loop will now display the gallery posts only.

After this, it’s just a matter of displaying what we want to display.

The main Loop itself is pretty straightforward. To display that featured image, we use essentially the same code as we used before, only passing it a bigger size.

To display the description, we just use the_content() as per usual. One thing we have to do though is to set the global $more value to zero, so that it stops at the !–more– tag, preventing it from continuing to display the whole gallery.

Getting the count turns out to kinda suck. There’s no good function in WordPress to do this for you easily. So, reluctantly, I resorted to an SQL query.

echo $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_parent = '$post->ID' AND post_type = 'attachment'" ) .' PHOTOS IN THIS SET';

The four thumbnails you can do using the get_children trick. However, there’s a catch. We don’t want to display the featured image as one of those four thumbnails. So, since we’ve already displayed that image (see the code above), we have the $thumb_id variable still. So we’ll use that to not get that image. Like so:

$attachments = get_children( array(
	'post_parent' => get_the_ID(),
	'post_status' => 'inherit',
	'post_type' => 'attachment',
	'post_mime_type' => 'image',
	'order' => 'ASC',
	'orderby' => 'menu_order ID',
	'numberposts' => 4,
	'exclude' => $thumb_id )
);
foreach ( $attachments as $img => $attachment ) {
	echo '<a href="'.get_permalink($img).'">'.wp_get_attachment_image( $img, $size ).'</a>';
}

By using the exclude parameter, we can get the first four images in the gallery without getting that featured image again, if it’s in those first four images.

Update

Andrew Nacin pointed out that I can combine the act of getting those four children and getting the attachment count into a single new WP_Query, like so:

$images = new WP_Query( array(
    'post_parent' => get_the_ID(),
    'post_status' => 'inherit',
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'order' => 'ASC',
    'orderby' => 'menu_order ID',
    'posts_per_page' => 4,
    'post__not_in' => array($thumb_id),
    'update_post_term_cache' => false,
) );

This creates a new secondary query that I can loop through like so, to show the children:

foreach ($images->posts as $image) {
	echo '<a href="'.get_permalink($image->ID).'">'.wp_get_attachment_image( $image->ID, $size ).'</a>';
}

It also has the side benefit of doing the primary counting of the images for me, via the SQL_CALC_FOUND_ROWS that WordPress uses in full-blown queries. However, the count will be off by 1, since we’re excluding the featured thumbnail. Therefore, I just have to add one to it:

echo ($images->found_posts+1) . ' PHOTOS IN THIS SET';

That combines both of those elements into one query instead of two, and eliminates the need for the direct SQL query.

(Side note: I also set ‘update_post_term_cache’ to false to prevent it from doing an extra query to get the terms for these posts into the internal memory cache. This saves us a bunch of unnecessary queries, since I’m not using the terms here anyway. Using full WP_Query objects instead of the simpler ones like get_children can take a little bit more thought and effort, but can save you time in the long run, if used wisely.)

Sizes

Throughout this post I’ve used $size as a generic indicator of where to put the size parameter. WordPress creates sized images by default, as we all know. These are thumbnail, medium, large, and full which is just the full sized uploaded image, unmodified.

But WordPress can create other sizes too, if you like. At different points throughout Matt’s gallery pages, you’ll see images displayed in all sizes. These sizes are custom, and they’re added in the functions.php file.

add_image_size( 'nav-thumbnail', 100, 100, true );
add_image_size( 'random-thumbnail', 200, 150, true );
add_image_size( 'gallery-thumbnail', 250, 200, false );
add_image_size( 'gallery-large', 660, 500, false );
add_image_size( 'gallery-pagethumb', 70, 70, true );

The add_image_size function takes a width, a height, and a flag to cause it to crop or not. So those tiny thumbnails on the gallery are “gallery-pagethumb” sized, and are 70×70, cropped. Anywhere I need one of those sizes, I can just pass that parameter instead of $size and voila.

Obviously though, adding too many sizes is undesirable, because it takes time to create those sizes (they’re created on upload of the images), and it takes storage space to store them. Hopefully a future version of WordPress can work around this issue.

Conclusion

These are the basics of making cool galleries, without plugins, without special uploaders, and while being able to style it to match your theme. Play with it. Experiment. There’s a ton of functions in WordPress specifically for dealing with these. Take a look through wp-includes/media.php and look at some of the function names. You might be surprised.

Shortlink: