Categories
24 Days of WordPress Tutorials WordPress WordPress Themes

Day 24: Vidunder – a Free WordPress theme just for you

I promised something big, and here it is. On this 24th and Last Day of WordPress (for 2010 at least) I give you the new Vidunder WordPress theme that you see running on this very blog.

Download Vidunder right here!

More customization than you’ll ever need

Vidunder (means “wonder” in Norwegian) is a Twentyten child theme that takes what Twentyten does and builds on it. There are so many customization options in this theme it’s hard to list them all but here are the highlights:

Custom colours

The colour scheme of Vidunder is by default orange. But you can change it to any colour you want. Simply go to Appearance -> Background and change the colour. This will change the background colour as well as the link colours and some other elements.

Custom logo

To change the logo go to Appearance -> Header and upload your own. The logo is 87 x 87px and if you want a transparent logo like the one you’re seeing here you need to upload a PNG of exactly that size. If you don’t care about transparency you can upload any image file and WordPress will help crop it to size for you.

Twitter updates in the header

To activate Twitter updates in the header go to Settings -> General, scroll to the bottom and enter your Twitter handle. The theme will go to Twitter, get your latest tweet and display it in the header for you.

Custom header image

Using the Appearance -> Background setting you can also upload a custom header image of your choosing. This is independent of the custom colours.

Custom Author Box

Custom Author Box and Related Posts

To display the Custom Author Box underneath single posts go to Users -> My Profile and define your name, email address, website, bio and Twitter handle (yes, Twitter handle). The author box will grab your Gravatar and display it along with your info. If you don’t have a bio defined the Custom Author Box will not show.

Related Posts

If there are two or more posts in the current category the two latest ones will be displayed under the current post. The Custom Author Box and the Related Posts box can be hidden by the viewer by clicking the Hide button in the top right corner.

Sidebars Gallore

The theme features 9 widgetized areas. In addition to the standard twentyten areas there is Custom which is a full-width area jammed up against the header. You can see it displaying the graphic ads for my books and video series here. Use it with causion. In addition there are Left and Right. Experiment at your own leisure.

And last, but not least…

Download Vidunder right here!

God Jul og Godt Nytt Ã…r!

Now go install Vidunder, mess around with the settings and get your WordPress site going for the new year!

Categories
24 Days of WordPress Tutorials

Day 23: 24 Hours of Free Lynda.com Access + The World’s Best Turkey

On this 23rd Day of WordPress I figure you are pretty well tied up in planning for the holidays and not really in the mood to get down and dirty with some hard core code examples. So I have something a little bit different for you: 24 hours of free access to Lynda.com and all its amazing tutorials! (Don’t follow the link now unless you have 24 hours to spare. Wait until you can sit down and relax in front of your computer for a full day undisturbed) That way you can take the time during the holidays to sit down and devour my WordPress 3 Essential Training course along with the hundreds of other fantastic videos on the site. I strongly recommend you set aside a full day for this and that you have a large pot of coffee handy because there’s a lot to learn in Lynda’s libraries and the pass really only lasts for 24 hours.

Be sure to come back tomorrow for the huge finale of this article series. Trust me, you will not be disappointed.

And now for something completely different:

How to cook a perfect turkey

So, seeing as I don’t technically have a tutorial for you today I decided to serve up something else instead: How to cook a perfect turkey. This is actually my father’s recipe, honed and refined over many years, and for the last 8 years I’ve been following it to the letter for raving reviews. And now you can too!

This recipe covers both turkey and stuffing. I recommend getting the turkey one size too big so you are guaranteed leftovers for sandwhiches the next day.

Ingredients

  • Turkey (I get Butterball – it’s been a success every time)
  • Ground beef (500g is good for 5-6 people)
  • Ground pork (same ammount as the ground beef)
  • Whole oats or dry bread crumbs – 1/4 the volume of the combined meat
  • 4 – 6 eggs
  • A block of butter
  • Cream and/or homo milk or another rich type of milk
  • Oregano
  • Merian
  • Thyme
  • Rosemary
  • Salt & Pepper
  • A splash of Port wine
  • A bottle of cheap sweet white wine
  • Gravy
  • Lingonberry jam (get it at IKEA) or in a pinch cranberry jelly
  • One onion per person
  • Two potatoes per person
  • Carrots and some other greens

Tools

  • A sharp knife, preferably a fillet knife
  • Pliers
  • Large needle
  • Twine
  • Blender

Prepping the turkey

Thaw the turkey in the fridge for around 4 days until it is not a solid block of meat. If you’re in a hurry you can thaw it in running cold water. Do not under any circumstances thaw it in the open by leaving it on the counter for a day. It will result in a visit to the ER for all your guests.

Once the turkey is thawed, look inside the neck area. Usually you’ll find a small bag containing the heart, liver and giblet as well as the neck. Take these out and place the neck to the side. Cut the heart in four pieces and remove the heart valves and any big fatty tissue or other hard bits. Next spread the giblet in three and cut off the white tendon material that is holding the pieces together. Toss the heart, giblet and liver in a blender and make a mush out of it. This will be added to the stuffing later for that signature turkey taste.

Now for the turkey. Take your knife and cut around the ends of the legs all the way to the bone. The goal here is to cut through the many tendons that run along the bone. Grab the tendons one by one with your pliers and run the knife carefully up under the skin along the tendons as far as you can. Be careful not to poke holes in the skin. Try to cut the tendons loose as far in as you can and pull them out. This is a seriously laborious task and it’ll take you at least 30 minutes for both legs. It seems unneccesary and frustrating, but the end result is well worth it: Tender, non-chewy drumsticks.

Making the Stuffing

When all the tendons are out (I think there are at lest 6 or 8 per leg – two big ones and a pile of small ones) it’s time to make the stuffing. Take the beef and pork and mix it together (pork has less taste btw so if you want to have more of a turkey flavour add more pork and less beef. For the last few years we’ve gone 100% pork). Cut out a quarter of the meat and fill the space with whole oats, then add the meat in again. Mix in eggs (4 for a small turkey, 6 for a large one), some cream, a splash of port wine and a mix of spices. This is a bit of a trial and error type thing so feel free to experiment. Finally add in the mush from the turkey innards and mix the stuffing until it has a homogenous consistency.

Stuffing and stitching the turkey

Grab your block of butter and cut out a bunch of flat pieces. With the bird breast up run your hands up under the skin of the turkey to separate it from the meat and place some nice large chunks of butter on each of the breasts, on each of the thighs and some other meaty places. This will make the meat more moist. With the butter in place stuff the turkey full of the stuffing. Fill the cavity from behind and then add in from the neck as well. If there is any stuffing left wrap it in aluminum foil so it won’t burn and place it next to the turkey in the oven.

When the turkey is properly stuffed, grab your big needle and twine and stitch it shut. You want to close all the holes completely so do your best Frankenstein stitching here. The goal is to make the turkey leak-proof to keep all the moisture inside. Finally tie the legs together and run some twine around the whole bird to tie the wings tight to the body. Basicaly you want to turn the bird into a big football so it cooks better.

Final touches

Take your turkey football and place it in a tray. Place the leftover stuffing next to it along with the neck wrapped in aluminum foil (if you want to eat it) and fill the rest of the tray with quartered onions, sliced potatoes, carrots and other stuff.

Preheat the oven to 440 degrees Fahrenheit. Right before you put the turkey in the oven, crack open your bottle of cheap sweet white wine and pour the entire thing over the turkey so that the liquid stays in the pan. Cover the bird with aluminum foil so it doesn’t burn and put it in the oven on the bottom rack. The sugars in the wine will plug all the pores in the skin of the bird and keep more of the moisture inside. As a bonus the wine also gives the turkey a nice taste and smell.

When the liquid around the turkey starts to bubble, lower the temperature to 350 degrees and let it cook for a long time (about 1 hour per kilo, so probably 5 – 6 hours depending on the size).

For the last half hour take the aluminum foil cover off to brown the turkey. If you have a cooking thermometer stick it in the thickest part of the breast to make sure it’s cooked properly. If not, leave it in longer.

When the turkey is done, take it out, remove the twine and cut it up. If it was cooked properly the thighs should pretty much fall off when you touch them. Because the stuffing is made of pork I safe it by nuking it a bit in the microwave just to be sure.

Serve the turkey with the potatoes, onions and other goodies from the pan as well as gravy, jam and whatever else you want.

Lykke til!

Categories
24 Days of WordPress Tutorials

Day 22: Custom Fonts with FontSquirrel.com

In Custom Fonts with Google Fonts I explained how to add custom fonts from the Google Font Directory to your WordPress site. The problem with the Google Font Directory is that it only has a limited (but growing) supply of fonts and that some of them are not very nice to look at when they get rendered in live text. Fortunately there are alternatives. My favourite is Font Squirrel. Font Squirrel offers up a huge list of free fonts ready for embedding and many of them are very nice and functional. That said I recommend using some of the more extreme fonts for headings only – setting your entire text content to a handwriting font or something really big and blocky has the potential of driving your readers away.

Adding a font from Font Squirrel requires a bit more work than adding a Google Font Directory font, but don’t fret – it’s not hard at all and the end result is well worth the effort.

1. Find a font on FontSquirrel.com

An obvious question when embedding fonts in your site is “Why can’t I just add any font I want?” The answer is a bit complicated, but here is the gist of it: Fonts are intelectual property, just like a photo, a video or a piece of writing. As such the creator can decide who can and cannot use a font and what the font can be used for. Generally speaking most fonts can be used on the web in one form or another, but there are a lot of famous and popular fonts that can not be embedded in a site using @font-face. To find out what fonts can and cannot be embedded, and whether you need to pay a licencing fee to use a font you have to read the licencing agreement for that particular font. And trust me, those things are legal behemoths and no fun to read.

A better option is to safeguard yourself by only using free open-source fonts. This is where Font Squirrel comes in. When you go to the site, click on the button that says #font-face Kits. From here you can browse all the fonts Font Squirrel have found, compiled and prepared for @font-face embedding, and better yet Font Squirrel has already dug through the licences of these fonts to make sure they allow embedding. In other words someone else did all the hard work and all you have to do is use the font (even so you should read the licence just to be sure). And the best part? The fonts are (mostly) free!

So, you go to FontSquirrel.com, click on @font-face Kits and find a font you like. Now comes the fun part.

2. Get the @font-face kit


Font Squirrel
Once you’ve found a font you like, say New Athena Unicode for example, click on it and you are taken to the page for that font. From here you can look at specimens, test drive the font with your own text (good idea if your language includes weird characters like ß, æ, ø, Ã¥, or other linguistic anomalies), look at a charecter map, read the licence for that font and get the all important @font-face kit. If you are happy with your selection click the @font-face kit button. From here you can select a subset (default is usually fine) and pick what font formats to include. I recommend including all the formats to sensure that as many browsers as possible will be able to read your fonts. With all your settings done click Download @font-face Kit and you get a zipped file to be saved on your computer.

3. Using the @font-face Kit

To use the @font-face kit you need to do three things: Add the font files and font stylesheet to your site (I recommend putting them in a dedicated folder under your theme), call the custom stylesheet from your header.php file and add the call to the font from your theme stylesheet. Here is that process step by step:

First go to your theme folder and create a new folder. For future reference I recommend naming the folder the name of the font so in my case that is NewAthenaUnicode. Extract all the content from the zipped archive and place it in the new folder. Now you should have a folder with 3 or more files including demo.html, a text document with licencing information, one or more font files (ttf, eot, svg, woff) and a stylesheet named stylesheet.css.

Next you need to call the stylesheet from your header.php file. Like we did with the Google fonts open your header file and find the call to your normal stylesheet:

Create a new line directly above and insert a link to your custom font stylesheet. To make this foolproof use the WordPress template tag to define the stylesheet address and then just add the folder you created along with stylesheet.css to it. If you are working with a standard theme it will look something like this:

If you are working with a child-theme you have to use a different template tag and the code will look something like this:

Save the header.php file and upload it along with the custom font directory to your web host and visiting browsers will now call the new fonts and have them ready to be used.

The last step is to add your new custom font to styles in your theme stylesheet so they are displayed. To find the correct name for your font first open the stylesheet.css file found in your custom font directory and look at the @font-face style definition. For New Athena Unicode Regular it looks like this:


@font-face {
	font-family: 'NewAthenaUnicodeRegular';
	src: url('new_athena_unicode-webfont.eot');
	src: local('☺'), url('new_athena_unicode-webfont.woff') format('woff'), url('new_athena_unicode-webfont.ttf') format('truetype'), url('new_athena_unicode-webfont.svg#webfontTqKRtuvj') format('svg');
	font-weight: normal;
	font-style: normal;
}

What you are looking for here is the font-family name which in this case is NewAthenaUnicodeRegular. Now all I have to do is put this name into my font family calls throughout my theme stylesheet and the new font will be used. As an example to add the new font to the paragraphs of this site the p style would look like this:


p {
	font-family: 'NewAthenaUnicodeRegular', Times New Roman, Times, serif;
	font-size: 0.8em;
	color: #333333;
	margin-bottom: 10px;
	text-align: justify;
	line-height: 1.5em;
}

As you can see using custom fonts from Font Squirrel in your WordPress site is relatively easy and can give your site a whole new look. Yes, it is more cumbersome than using the Google Font Directory, but not by much, and in return you have far more fonts to choose from.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 21: Add Custom WordPress 3 Background Functionality to Your Theme

If you’ve been playing around with the twentyten theme at all you will have noticed that under Appearance you have a new function called Background. From here you can set a background colour or upload a photo to be used as the background, either tiled or by itself. On this 21st Day of WordPress – which happens to be Winter Solstice – I’ll show you how to add this very cool function to other WordPress themes.

Adding the Custom Background function to your theme

The custom background function was introduced in version 3 of WordPress and consists of a single function call placed in functions.php of your theme. It looks like this:


add_custom_background();

Add it to your functions.php file, save the file, upload it to your server and you now have the custom background function. Simple as that.

What does the custom background function do?

When in use the custom background function adds some new style code for the body tag at the very end of the head tag of your pages. This is strictly speaking a bit of a dirty way of achieving the goal, but it works and it is in compliance with web standards. The style code is dynamically created based on how you configure the Background settings and will looks something like this:


<style type="text/css">
body { background-color: #4547de; background-image: url('http://yoursite.com/wp-content/uploads/2010/12/backgroundimage.jpg'); background-repeat: repeat-y; background-position: top left; background-attachment: scroll; }


Because it’s called at the very end of the head of the page it overrides any background image or colour styling in your regular stylesheet.

The background image function is very useful for theme developers because it gives the end user the ability to muck around with the background as much as they want without having to deal with all that pesky CSS code stuff. Nuff said.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 20: Using JavaScript Libraries in WordPress the Right Way

If you have worked with WordPress either as a stite owner or a developer you have likely run into situations where you add a plugin or a new theme only to find that some functions that previously work no longer work. This is in almost every case caused by JavaScript conflicts where the same library (or more often different versions of the same library) is called numerous times to do different jobs. The end result is a JavaScript conflict where nothing works.

What most poeple, WordPress developers included, don’t know is that WordPress comes pre-packaged with a whole whack of JavaScript libraries ready to be called and utilized. On this 20th Day of WordPress I’ll show you an example of how to utilize one of these libraries through the use of the wp_enqueue_script() function.

Hiding and revealing the comment section with jQuery

For a project I worked on earlier this year there was a feature request for the comments section to be hidden by default and then revealed only when the visitor clicked a link. The designer wanted the comments to be revealed using a smooth sliding reveal function. jQuery has just such a function, called .slideToggle().
We can write a simple function that will achieve our goal. It looks like this:


jQuery(document).ready(function($){
	$(".commentsKicker a").click(function(){
		$("#comments").slideToggle('slow');
		return false;
	});
});

The script looks for container with the class .commentsKicker that has a link in it and when that link is clicked, the contents of the div with the ID #comments will be revealed slowly using the .slideToggle() function.

To implement this script two things need to happen. First the jQuery librar has to be innitialized and then the function above needs to be set up. Common practice is to do this by placing a new jQuery library in the theme file, usually under a folder called “js”, calling it from the header.php or footer.php file and copying the function above straight into the same file. This is both clunky and completely unneccesary. A better option is to save the above script as a .js file in your theme and use wp_encue_script() to not only load the custom function but also associate it with the jQuery library WordPress carries with it.

Setting it all up with wp_encue_script()

Before we do anything else, let’s make sure we’re on the same page. In my single.php file I’ve placed a span with the class .commentsKicker and within it is the regular comments_popup_link() function. The comments section (to be hidden and then revealed) is wrapped in the regular #comments div (this is a WordPress theme default). Finally I’ve created a sub-folder in my theme directory called JS with a file called “reveal.js” that contains the JavaScript function displayed above exactly as it is displayed above.
With all that settled we can create a new function in functions.php that will at once call our custom JavaScript file, associate it with the stock jQuery library and enque both in our theme so they become active. Let’s do it step-by-step:
In functions.php of your theme create a new function:


function revealComments() {

}

Add an if statement to prevent the script from loading on admin pages:


function revealComments() {
	if (!is_admin()) {
	}
}

Register our custom script by giving it a name, defining its location and its library dependency:


function revealComments() {
	if (!is_admin()) {
		
		wp_register_script(
			'reveal',
			get_bloginfo('template_directory') . '/js/reveal.js',
			array('jquery') );

	}
}

Enque the new cusom script so WordPress can use it:


function revealComments() {
	if (!is_admin()) {
		
		wp_register_script(
			'reveal',
			get_bloginfo('template_directory') . '/js/reveal.js',
			array('jquery') );
		wp_enqueue_script('reveal');
	}
}

Finally, add an action that tells WordPress to initiate the new function upon first load:


function revealComments() {
	if (!is_admin()) {
		
		wp_register_script(
			'reveal',
			get_bloginfo('template_directory') . '/js/reveal.js',
			array('jquery') );
		wp_enqueue_script('reveal');
	}
}

add_action('init', 'revealComments');

With the new function and action in place the cutom JavaScript will automatically load and the fancy hide/reveal effect is added to the posts.

Further reading

The wp_enqueue_script() function is hugely effective and allows for a lot of advanced functionality. WordPress carries with it a whole slew of different JavaScript libraries and even if the library you want to use is not bundled into the application you can use wp_enqueue_script() to add other JavaScript libraries. The bottom line is if you want to use JavaScripts in your WordPress themes you should do it properly by way of wp_enqueue_script(). To get a full understanding of the function, its variables and many uses check out the WordPress Codex page.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 19: Creating a Blog Within a WordPress Site

One of the great advantages of working with WordPress is that it has a blogging platform built right in. Some would argue that this is because WordPress is a blogging platform but I disagree. WordPress is a content management system that in its past used to be a blogging platform. But that’s and argument that is a total waste of time. The only thing that really matters is this: You can use WordPress to build a site with multiple posts, categories and other content and still have a blog inside it. And on this 19th Day of WordPress I’ll show you how.

What do you mean “a blog inside it”?

Let me explain myself here so it’s clear what I’m talking about. Imagine you are building a site for an illustrator. The site has four static pages (front page, about page, CV, and contact) and she also has a series of posts stored under categories including portfolio, articles and tutorials, each with sub-categories. But in addition to these non-blog posts she wants a section on her site called “blog” where she can post all the stuff that doesn’t fit anywhere else.

To get all this to work we need to set up a new category called “Blog” with however many sub-categories she wants, create a page called “Blog” on which to display the blog index page and finally limit the posts displayed on the blog page to only posts listed under the Blog category or its children. So let’s get started.

Setting it up

Logged into WordPress create a new page called Blog. Don’t put any content in the page as it will be used as the blog index page.

With the new Blog page published go to Settings -> Reading, set Front page displays to A static page and select your home page (whatever it is) as your Front page and the Blog page as the Posts page (remember to hit Save Changes).
Changing the front page of a WordPress site

Displaying only posts from the Blog category

To get WordPress to only display posts from the Blog category on the blog index page you need to add a query to the index.php file. The query first checks if this is indeed the blog page (is_home) and then restricts the posts displayed only to those posts in the Blog category (using the slug “blog”) or its children:


If you want to use the category ID instead you can do so by changing the variable in the query like this (assuming the category ID in question is 3):


The query_posts() function has a lot of varialbes and there are tons of cool things you can do with it so I recommend checking out the WordPress Codex page for the function as a way to expand your coding horizons.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 18: Creating Custom Single Post Templates

So far in this series we’ve looked at how to creating and use Custom Page Templates and Custom Category Templates, but what about custom single post templates? As of right now, there is no built in function for creating custom single post templates in WordPress (though I believe it’s coming – at least partially – in version 3.1. In the meantime we can still create custom single post templates based on the categories a post belongs to, we just have to write the actual function for it as well. On this 18th Day of WordPress I’ll show you how to do just that.

Creating a Custom Single Post Template function

There are just two steps to this process: Create a function to activate custom single post templates and creating the actual template itself. Let’s tackle the first one first. What you need to do is wirte a function – to be placed in functions.php of your theme or child-theme – that grabs the category info for the post in question and checks if there is a custom single post template that matches that particular category. That function looks something like this:


add_filter('single_post_template', create_function(
	'$the_template',
	'foreach( (array) get_the_category() as $cat ) {
		if ( file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php") )
		return TEMPLATEPATH . "/single-{$cat->slug}.php"; }
	return $the_template;' )
);

This function, actually a filter, finds the category slug(s) for the post and checks if there is a template file called single-[slug].php in the theme. If there is, that tempalte is used in place of single.php. So for example if you have a category called Portfolio with the slug “portfolio” you can create a new file called single-portfolio.php that will then become the custom single post template for posts assigned to this category.

But… Isn’t there a plugin for that?

The question you are probably asking yourself right now is “Isn’t there a plugin for that?” And the answer is yes, there is. It’s called Single Post Template. So why am I making things difficult by serving up a function that needs to be added to the theme files? Two reasons: First off I don’t particularly like plugins because they tend to bog down sites and often create a big mess in the code. But more importantly, if you are creating a custom theme for distribution you can’t rely on people always installing a specific plugin. The method described here is much better because you can serve up custom single post templates for selected categories and then all the user has to do is create those categories and the template will kick in automatically. It’s clean, it’s simple and it’s foolproof.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 17: Using custom category templates and query_posts

Custom queryRight now I’m working on a site for a local video production company called Reeltime Videoworks. As part of the spec for the site was the ability for the owners Sue and Don to add testimonials to the site that would be featured on a testimonials page as well as in short version on the front page. There are many ways of doing this, and it can be done for a lot of topics, not just testimonials, but I chose to use a custom category template plus some nifty coding on the front page to make it all work. On this 17th Day of WordPress I’ll give you a preview of how it all fits together and some tips along the way to get you going on your own custom categories.

Mapping it out

Before starting on a project it’s a good idea to think through what is going to happen. That way you get a clear idea of how you want to store the information and where you want to display it. In this case I had three major components that needed to be addressed:

  1. The owners want to be able to add and manage testimonials easily
  2. All the testimonials should be displayed on a page as a list
  3. The front page should have a box where excerpts of testimonials appear, different each time the page is loaded

To make this all work I decided to go the easiest way possible: Make a category called Testimonials, create a custom category template for the Testimonials category and create a small query that pulls the excerpt from a random post within the Testimonials category and displays it on the front page.

Creating a custom category template

Custom Category TemplateI’m going to assume you know how to make posts and categories so I’ll jump right to creating a custom category template. Custom category templates are one of those well kept secrets of WordPress. Most people just ignore them completely and rely just on the main category template, but you can do a lot of fun stuff with the custom versions.

When it comes to what template to use when displaying a category list WordPress operates with a strict hierarchy:

  1. category-slug.php
  2. category-ID.php
  3. category.php
  4. archive.php
  5. index.php

This means to create a custom category template for a category called “Testimonials” all you have to do is create a copy of the category.php file and name it either category-testimonials.php or category-ID.php (where ID is the numerical ID of that category) and you’re ready to start customizing.

Now the whole point of creating a custom category template is that it displays differently than other categories. In the case of this project I wanted a picture of the quoted person with his or her name and company affiliation displayed on the right with the actual quote displayed on the left in a stylized form. To make things as easy as possible for the Reeltime crew I set it up as follows:

  • The post title is the name of the person
  • The post body is the quote itself
  • The post excerpt is the best part of the quote to be displayed on the front page
  • A custom field is added with the key companyTitle that is filled with the company title and affiliation info
  • The photo of the person or a company logo is added as the Featured Image

The custom category template in turn calls the information and puts it in the page in the order I want it. For your reading pleasure (or confusion?), here is the actual loop from the template:


<?php while ( have_posts() ) : the_post() ?>
	<div class="testimonialPost group">
		<div class="testimonialThumbnail">
			<?php if ( has_post_thumbnail() ) {
				the_post_thumbnail('thumbnail');	// the current post has a thumbnail
			} else {
				get_thumbnail($post->ID, 'thumbnail', 'alt="' . $post->post_title . '"');
			}
			?>
			<div class="label">
				<div class="name">
					<?php the_title(); ?>	
				</div>
				<div class="company">
					<?php echo get_post_meta($post->ID, 'companyTitle', true); ?>
				</div>
			</div><!-- END .label -->
		</div><!-- END .testimonialThumbnail -->
		<div class="bigBubble">
			<?php the_content(); ?>
		</div><!-- END #bigBubble -->
	</div><!-- #testimonialPost -->
<?php endwhile ?>

The result is the display you see above. Note how none of the items contain a link to the actual post for that quote. The only way anyone will ever land on a single post view of the item is if they get there through a search engine or a lucky guess with a URL. And if they do they land on a custom post template, but that’s a whole different tutorial.

Displaying the excerpt from a random post on the front page

A testimonialNow that the custom category template is in place and there are testimonials, the next step is to display the excerpt and the name and company affiliation of one person on the front page, and display a random one each time the page is loaded. For this we need to make a custom query on the front page. And for that we use the very useful query_post() function.

The query_posts() function allows you to dictate exactly what posts WordPress should poll when a certain action happens. In this case I created a query to go in a custom page template for the front page that did three things at once: Tell WordPress to only call one post, make that a random post, and call it from the testimonials category. Once the post is called I could run a standard loop on it. And when the loop is finished the code wraps up by resetting the query. You’ll notice in the code below that though the loop is different it is displaying roughly the same content as the previous code example:


<?php
query_posts('showposts=1&orderby=rand&category_name=testimonials'); 
	
	if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
		<div id="bubble" class="group">
			<div id="bubbleCenter" class="group">
				<?php the_excerpt(); ?>
			</div><!-- END #bubbleCenter -->
			<div id="bubbleBottom" class="group">
				<div class="name">
					<?php the_title(); ?>
			        </div>
				<div class="company">
					<?php echo get_post_meta($post->ID, 'companyTitle', true); ?>
				</div>
			</div><!-- END #bubbleBottom -->
		</div><!-- END #bubble -->
	<?php endwhile; endif;
 
wp_reset_query();
?>

The proverbial tip of the iceberg is right here

What I’ve done here is just a small taste of what you can do with some creative uses of custom category templates and queries. Using similar setups I’ve created photo galleries that poll Flickr sets, video galleries that show videos in lightboxes and even post galleries that show up as photo galleries using the Featured Image function. This is one of those times when the only limitation really is your imagination.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 16: Using custom headers, sidebars and footers

On this 16th Day of WordPress I bring you something more akin to a useage example than a tutorial. It concers the inbuilt ability in WordPress to handle multiple versions of the header.php, sidebar.php and footer.php files for customization purposes. The process of building and calling these files is a snap, so rather than wasting your time just giving you the codes I’m going to give you some ideas on how you can use them for better customization.

A semantic approach to the php include

When you work with WordPress themes you encounter custom WordPress funcitons all the time. Three functions you are likely to see on almost every template page are:


<?php get_header(); ?>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

These functions inject the contents of header.php, sidebar.php and footer.php respectively directly into the template file as if they were part of the original file.

The get_ functions are actually custom variants of the generic include function found in PHP. You could rewrite them as


<?php include('header.php'); ?>
<?php include('sidebar.php'); ?>
<?php include('footer.php'); ?>

and get the exact same results.

So why use the get_ functins at all then if the include function does the same thing? The answer is twofold: First off the get_ functions are semantically more readable. While the include function needs a proper URL to work (you can use it to call any file using relative, root-relative or absolute links) the get_ functions require no further expansions or variables unless you want to go the custom route. That brings us to the second reason which is that the get_ functions are not limited to just the core files. Let me explain.

Custom get_ calls for custom files

A little known ability of the get_ functions is that you can use them to call custom header, sidebar and footer files. It’s a simple two-step process. I’ll use header.php as an example:

  1. Create a new file called header-custom.php
  2. In the template file from which you want to call the new custom header file add ‘custom’ as a variable to the regular get_header() function like below

<?php get_header('custom'); ?>

Now WordPress will use header-custom.php instead of header.php. The exact same method goes for sidebar.php and footer.php as well.

Why do this? Because the possibilities are endless!

Now that you know how to call custom header, sidebar and footer templates let me give you some ideas on how to use them, starting with the header.

The header.php file usually contains all the head information of your pages including things like stylesheet calls, feed links and core JavaScript libraries. But what if you had a custom page template, a certain category or even a post type on which you wanted to use an alternate stylesheet? Of course you could write in a conditional script to pick stylesheets depending on what page or post is being opened, but an easier route would be to simply create an alternate header file with an alternate stylesheet link that was called by that particular template. Another common scenario would be when certain sections of the site require a custom menu. Or let’s say you want to offer up additional features to visitors who are logged in. Again the custom header file would be of great help.

What of the sidebar then? I actually use custom sidebars in my sites all the time because they provide almost limitless flexibility. By having mutliple sidebar files with different configurations I can provide my clients with multiple page, category and even post templates that display one, two or three sidebars with varying widgetized areas. By creating widgetized areas that are only featured in certain sidebar files you can offer the site owner further flexibility when it comes to what info is displayed where on the site. Want a custom menu to appear in the sidebar on a certain page only? Create a custom page template and call a custom sidebar file. Simple as that.

That just leaves the footer. For most sites, the footer is just a repository for copyright information, closing divs and maybe a menu. But with some ingenuity you can take things a lot farther. For example you can offer up a custom footer file for the front page that also contains widgetized areas displaying menus, latest posts,
latest comments or other material. Or you can provide a custom footer for category pages that provide related post info.

You can do whatever you want here. I wasn’t joking when I said the possibilities are endless. A firm grasp on how to use and abuse the get_ function will be a welcome addition to your coding toolkit.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 15: Upgrading WordPress the manual way

This morning a friend was having serious dificulties upgrading his WordPress site from 2.something to 3.0.3. His cry for help reminded me I’ve never actually written a proper rundown on how to do WordPress upgrades the manual way, so on this 15th Day of WordPress that’s what we’ll be looking at.

When automatic upgrades don’t work…

His site, like all of mine, was hosted on 1&1 and he was running into two calssic problems: First WordPress wouldn’t update at all – the process just stalled after the files were downloaded. The second problem – far more complicated – was that the database for his installation was running MySQL 4.something which is too low for the newer versions of WordPress. Quite the conundrum. Well, not really: Just a massive headache. But it’s all fixable.

Just so it’s clear: The following information is host independent. I’m just using 1&1 as an example.

None of this comes with any warranties of any sort. Mess with your databases and settings at your own risk. I take no responsibility for any disasters here.

Upgrading the database

If you set up your WordPress site a couple of years ago chances are it is still running on a MySQL 4.x database which is no longer supported by WordPress 3.x. In other words, to keep your site safe and get the use of the latest and greatest WordPress has to offer you have to upgrade your database. Some hosting providers will let you automatically upgrade your 4.x database to 5.x, but a lot of them won’t. In other words you have to set up a new 5.x database, dump the old 4.x database and import the dump to your 5.x database, then rewrite your wp-config.php file to access the new one. Tricky, yes, but it’s a necessary evil of running a WordPress site, so let’s get crackin’.

Step 1: Create a new 5.x database

This step varies greatly and is entirely dependent on what hosting provider you are using. Usually you go to the MySQL admin area and click “Create new database” or something along those lines. Under 1&1 you go to Administration, MySQL Administration and click New Database.

Whichever method you use there are two vital components to this step:

  1. Make sure the new database is running MySQL 5.0 or greater
  2. Set a strong password. I use a random password generator and create 32 to 64 key passes every time. (oh, and remember to store the password somewhere for later retrieval)

Step 2: Create a dump of your old database

Next you need to get all the content from the old WordPress database so you can add it to the new one. To do this you have to go to phpMyAdmin and do a password dump. The WordPress Codex has a full rundown of how to do this but here’s how to do it on 1&1 if you don’t want to follow the link.

  1. Go to phpMyAdmin and find the database you want to back up
  2. Click Export to get to the export page (position of the Export option varies depending on host and phpMyAdmin version)
  3. Under Export you want the following options checked (see grab below):
    • Export type: SQL
    • Structure: Add DROP TABLE, Add AUTO_INCREMENT value, Enclose table and field names with blockquotes
    • Data: Complete Inserts, Use hexadecimal for binary fields
    • Save as file
    • Compression: None
  4. Click Go to save the file on your computer

Database Backup
The above process will produce a file on your computer that contains your entire WordPress database including all your settings.

Step 3: Import the old database content into the new database

Now you have to move the old database content into the new database. You may or may not encounter a snag here, but I’ll cover that as well.

To import the old database dump you first go to phpMyAdmin for your new 5.x database. From here you have to find the import function. As with the export function it’ll be found in different places depending on hosting provider and phpMyAdmin version. On 1&1 it’s located in the Query Window. To get to it click the SQL icon underneat the 1&1 logo and the query window will open (see grab below).

MySQL Query WindowIn the Query Window you’ll find the Import Files tab. That’s where you want to go. From here import the database file you exported earlier and your database should be populated without any difficulties.

Step 3b: I’m getting a SQL error! The sky is falling!

There’s a chance you’ll get a SQL error here. If you do, it’s most likely something along the lines of “Cannot create new database dbXXXXX because dbXXXXX already exists” or some such message. Infuriating, but as always there is a simple solution:

If you’re getting this warning it is because phpMyAdmin was a little too smart and added an entry into your backup telling itself to create a new database with the same name when the file was imported. It makes sense in certain cases, but not in ours so we need to get rid of it for everything to work.

First, make a copy of your backup file just in case. It’s always a good idea to make extra backups. Then open the backup file in your favourite text editor. I use Notepad++. Somewhere towards the top of the file you’ll find something similar to these two lines of code:

Create DatabasephpMyAdmin sees these two lines and goes “Oh, I need to create a new database with this name. But wait, this current database has a different name, and the database name it’s asking me to use is already being used by another database. I’m confused. Error. Error. Error.”

So, to unconfuse the server simply delete these two lines and try importing the database again. Unless there is some other unknown issue it should work just fine now. If it does, we can move on. If not, call your host and ask for help.

Step 4: Setting up WordPress to talk to the new database

With the old database content running on a fresh new 5.x database we can do what we set out to do initially: Upgrade WordPress manually. This is where the comparmentalized nature of WordPress truly shines. You see, you can upgrade WordPress manually by simply deleting all the old files of the installation and replacing them with new ones (with the exception of the wp-content folder – I’ll get to that in a second). Since all your content and configurations is housed in the database, WordPress itself is replaceable.

First off, get the newest version of WordPress from WordPress.org. WordPress’ upgrade frequency is pretty high these days so don’t trust even a week-old copy. Next do a standard WordPress setup by configuring wp-config.php:

  1. Open wp-config-sample.php in your text editor
  2. Go to line 19 and insert the database name of your new database
  3. Go to line 22 and insert your database username
  4. Go to line 25 and insert that long password we created towards the beginning of this tutorial
  5. Go to line 28 and insert the database host name if necessary (your host will tell you if it is)
  6. Visit https://api.wordpress.org/secret-key/1.1/salt/ to get fresh Salt for your installation
  7. Copy the entire bulk of code you find on the Salt page
  8. Highlight lines 45 to 52 in wp-config-sample.php, delete the code and paste in the Salt you just copied in step 7
  9. Save the file as wp-config.php

Now the new version of WordPress will talk to your new database. All that’s left is updating WordPress itself. We’ll do this through FTP.

Step 5: Upgrade WordPress through FTP

Before you follow the next steps make sure you make a backup of the entire wp-content folder on your computer. This folder contains your themes, plugins and all uploaded files (images, music etc). During the upgrade process this folder is off limits.

  1. Launch your favourite FTP application and log in to where you have your WordPress installation running
  2. For safety, create a new folder called OLD in which we’ll dump a backup of your old WordPress install
  3. Check if you have a file called .htaccess or php.ini in the root folder. If so, leave them alone
  4. Highlight all the files as well as the wp-admin and wp-config folders
  5. Move the highlighted files and folders to the OLD folder
  6. You should be left with 2 folders: OLD and wp-content plus possibly the .htaccess and php.ini files
  7. Find your freshly downloaded WordPress verison with the new wp-config.php file on your computer
  8. Highlight all the files and folders except wp-config-sample.php and the wp-content folder
  9. Copy the highlighted files to your host through FTP

When all the files are uploaded to your host, WordPress should work again.

Step 6: Logging in for the first time

If you visit the front page of your site now it should be working as before. If you try loging in through the backend (www.yoursite.com/wp-admin) you’re likely to get a message that you need to upgrade the database. That’s normal and automatic so just click the upgrade database button. When the upgrade is completed you can log in and everything should be working fine.

Upgrade and plugin problems with 1&1 hosting

If you’re hosted on 1&1 you have likely run into two problems: First off, you can’t seem to get automatic upgrade to work. It just stalls. Secondly you may be getting some really annoying error messages when you use plugins like NextGEN Gallery. These problems are caused by RAM restrictions and security settings, and both can be fixed by adding two files to your root folder:

First you need to add a single line of text to the .htaccess file:

AddType x-mapp-php5 .php

This tells the server that it is indeed running MySQL 5. I have no idea why this is necessary, but it is. You may already have a .htaccess file with a bunch of content in it on your host. In that case download the file and add the line above to it before uploading it again.

Step two is to add a php.ini file to the root of your installation. Create a file called “php.ini”, open it in your text editor and paste in the following lines of code:

allow_url_fopen = on
register_globals = Off
memory_limit = 32M

This allows WordPress to write to itself and ups the memory limit so automatic upgrades and other functions can run properly.

With the .htaccess and php.ini files uploaded to your site everything should finally be working. If it’s not, give your host a call and get them to help you out.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 14: Posts Within Posts – Playing With The Loop

When I started 24 Days of WordPress I put out a call to my followers on Twitter and asked what they wanted me to write about. I got several responses asking for a tutorial on how to mess with the loop, so that’s what I’m going to give you today on this 14th Day of WordPress.

Displaying posts from the same category within a post

In this tutorial I’m going to give you a very specific example of a method that is open to a wide variety of configurations and outcomes. It is based on the loop I created to serve up the featured images pointing to other video posts within the same category in the Philip Lanyon website mentioned in Day 13’s tutorial on Featured Images. The basic idea is this: When you open a single post WordPress displays selected content from the most recent published posts from the same category at the bottom. I say “selected content” because with this method you can call any part of the content you want, from just the title or the featured image to the entire post. This is accomplished by setting up an extra loop within the post that jumps out of the post, finds the other posts in the same category and lists them.

Setting up the loop

Before we set up the loop we need to create a bacup of the current post ID so that we can call it and WordPress doesn’t get confused about what to display:


<?php
	$backup = $post; //backup current object
	$current = $post->ID; //current page ID
?>

The first line creates a new variable called $backup and fills it with the content of $post which is the current post you are on. The second line creates a new varialbe called $current that is set to the post ID of the current object. We’ll use this variable to make sure the current post isn’t listed again.

Now we need to set up a loop. I’ll give you the code first and then explain what it does:


<?php
	global $post;
	$thisCat = get_the_category();
	$currentCategory = $thisCat[0]->cat_ID;
	$myposts = get_posts('numberposts=2&order=DESC&orderby=ID&category=' . $currentCategory);
	foreach($myposts as $post) :
	setup_postdata($post);
?>

... do something with the loop output ...

<?php endforeach; ?>

From top to bottom this pile of code (1) tells WordPress we want all the data related to the current post, (2) creates a new variable called $thisCat that is filled with the category ID(s) for the current post, (3) creates a new variable called $currentCategory that is filled with the first category ID from the list, (4) creates a new variable called $myposts that makes a loop that displays two posts in decending order based on their ID numbers from the category defined in $currentCategory, (5) creates a loop that sets the ID value of $post to the ID value of $mypost and finally (6) sets up the postdata (so all the content) of the new post.

Still with me? Good.

OK, so now we have a loop that finds the other posts in the category and displays them. The key funciton here is actually the get_posts() function and to change something (like the number of posts displayed or the order) you tweak the variables of that function.

Resetting the $post ID

Before we get deeper into this, let’s reset the $post ID so WordPress doesn’t get confused about what’s going on. You’ll remember at the beginning we created a variable called $backup? Now we need to set $post back to $backup. That way we can call things like comments from the main post after the loop has run it’s course:


<?php
	$post = $backup; //restore current object
	wp_reset_query();
?>

Making it work

If you run this script in your single.php file now you should get two sets of the text “… do something with the loop output …” appearing in your post. That means it’s working. Now all that’s left is to call some of the post content and display it. The following code goes in place of “… do something with the loop output …” and displays the post title, post date and excerpt with the post title as a link:


<h2><a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark"><?php the_title() ?></a></h2>
<div class="date"><?php the_time('F j, Y'); ?></div>
<div class="theExcerpt"><?php the_excerpt(); ?></div>

Run this in WordPress and you’ll see that now you get a listing of the two most recent posts in this category with title, publication date and excerpt right inside your current post. Cool, eh? But there is still one problem: If your current post is one of the two most recent posts, it’ll be displayed twice. That’s just confusing, so we have to fix it.

Excluding your current post from the loop

At the very beginning of this tutorial we created a backup for the current post item and we also grabbed the current post ID. Now we’re going to use that current post ID to exclude the current post from the new loop. To do this we have to change the get_posts() variable to add an exclude variable:


$myposts = get_posts('numberposts=2&order=DESC&orderby=ID&category=' . $currentCategory . '&exclude=' . $current);

With the exclude in place we now have a fully functional loop that doesn’t create duplicate content.

OK, so where do I put this thing?

You probably have a pretty good idea what I am thinking here: In the twentyten theme you currently have a link to the previous and next post at the top and the bottom of each post. I find this quite unuseful and it’s also a bit of a pleonasm. So here’s what I suggest (and a warning here: You’re going to have to do some styling on your own to make this look decent): In your twentyten child theme create a duplicate of the single.php file, find and comment out lines 57 to 60 and paste in this new block of code instead. That way when people land on your pages they’ll get a preview of the two most recent articles written within this same category. If that’s not added value I don’t know what is.

Here, in case you got confused, is the entire loop code:


<?php
	$backup = $post; //backup current object
	$current = $post->ID; //current page ID
?>
<?php
	global $post;
	$thisCat = get_the_category();
	$currentCategory = $thisCat[0]->cat_ID;
	$myposts = get_posts('numberposts=2&order=DESC&orderby=ID&category=' . $currentCategory . '&exclude=' . $current);
	foreach($myposts as $post) :
	setup_postdata($post);
?>
<div>
	<h2><a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark"><?php the_title() ?></a></h2>
	<div class="date"><?php the_time('F j, Y'); ?></div>
	<div class="theExcerpt"><?php the_excerpt(); ?></div>
</div>

<?php endforeach; ?>

<?php
	$post = $backup; //restore current object
	wp_reset_query();
?>

Go forth and create loops my friends!

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 13: Using the Featured Image (Post Thumbnail) function in WordPress

WordPress comes with a lot of hidden or lesser known features that when used correctly can produce some pretty interesting results. One of these features is the Featured Image, or Post Thumbnail, funciton. On this 13th Day of WordPress we’re going to take a look at the Featured Image function and see how to activate, incorporate and use it in different ways in a custom theme.

Just to clarify before I begin: The naming convention here is really confusing: In the past this function was called “Post Thumbnail” because it dealt with the thumbnail. With the introduction of newer versions of WordPress, most notably version 3.0, the name of the feature has been changed to “Featured Image” while the function is still called “Post Thumbnail”. This is further confused by the fact that you can call the thumbnail size of a featured image as well as medium, large and original sizes. In short, the “Post Thumbnail” name is somewhat out of date and misleading. I’ll be using “Featured Image” throughout this tutorial because it is far more accurately descriptive.

Useage examples – thinking out of the box

The Featured Image and Post Thumbnail function is an often overlooked feature that can add a lot of functionality to a theme if used correctly. With the release of the twentyten theme it has come more to the forefront because it is used in the huge image in the header, but that’s just the tip of the iceberg of what is possible. Let me give you an example:

PhilipLanyon.com front pageWhen working on the PhilipLanyon.com project we were faced with a tricky spec: Philip wanted the front page of his site to feature an assymetric grid showcasing screen grabs of his latest uploaded videos. To make it more complicated he wanted these grabs to shift to the right and down as he added new videos and he also wanted them to appear as thumbnails under the playing video when on a single video page.

PhilipLanyon.com thumbnailTo accomplish this we created a series of custom featured image types that were called by the different areas on the site. That way when Philip added a new video all he had to do was upload one featured image along with the video embed code and the correct image size would be displayed in the correct area of the site when that page or post was opened. The result was a site that looks cool and is easy to manage at the same time.

Activating the Featured Image function

Before we can do anything else we need to activate the Featured Image function. If you’re not sure whether the function is active or not, take a look in the right sidebar of your edit page. If you don’t see a tab named Featured Image there, the featured image funciton is not active in your theme.

The base function to activate the featured image function, to be placed in functions.php of your theme file, is:


add_theme_support( 'post-thumbnails' );

This allows you to attach a custom featured image to each of your posts and pages through the Featured Image tab.

In-app configuration of the Featured Image function

Featured Image sizesIf you are using the featured image function as above you can control its output from within WordPress, more specifically you can control the sizes of the various outputs from the WordPress Admin panel:

Under Settings -> Media you’ll find three fields you can fill in: Thumbnail size, Medium Size and Large Size. These can be set to any width and height value you choose and when the various sizes are called they are displayed.

Here’s something you may not know: When you upload a photo to WordPress, the application creates three or more new versions of that photo for you in addition to the original: a thumbnail (normally cropped to a square), a medium size and – if the original is larger than the defined large size – a large size. And when you embed an image into your post or set a featured image, you can pick which one of these image versions you want to use.

Calling Featured Images from a template file

To get the featured image to display in your pages, posts, sidebar or whereever you want it you need to call it. This is done using the the_post_thumbnail() function of which the below is the base:


<?php the_post_thumbnail(); ?>

The above call will insert the thumbnail as defined when you set the featured image (so if you set it to thumbnail, medium, large or original it’ll be displayed in the selected size). To avoid any major disasters you can specify what size you want, either from the predefined sizes or even by calling a custom size like below:


<?php the_post_thumbnail('thumbnail'); ?> // calls the thumbnail size
<?php the_post_thumbnail('medium'); ?> // calls the medium size
<?php the_post_thumbnail('large'); ?> // calls the large size
<?php the_post_thumbnail(array(xxx,yyy)); ?> // calls the defined size (xxx and yyy replaced with numbers)
</php>

Advanced configurations

The base function is, as indicated by the name, just the basis of a more advanced function. You can control all aspects of the featured image function from within the functions.php file with more advanced instructions:

To restrict the featured image function to only posts or pages use one of the two function calls below:


add_theme_support( 'post-thumbnails', array( 'post' ) ); // Add it for posts
add_theme_support( 'post-thumbnails', array( 'page' ) ); // Add it for pages

You can also force default thumbnail size. This is done with a different function as set out below:


set_post_thumbnail_size( 50, 50, true );

where you can change the values – width, height, cropped – to whatever you want (for cropped, true means it’ll crop the image from the middle, false means it’ll squeeze or stretch the image to fid in the defined size).

If you want to get even more advanced you can even define your own custom image sizes for specific template files:


add_image_size( 'custom-post-thumbnail', xxx, yyy );

To call this custom size you use the standard template tag with the name defined in the function:


<?php the_post_thumbnail( 'custom-post-thumbnail' ); ?>

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.