Categories
Speaking Engagements Tutorials WordPress

WordCamp Victoria Presentation: 10 Theme Hacks to Improve Your Site


Above is the slide deck for my WordCamp Victoria presentation entitled “10 WordPress Theme Hacks to Improve Your Site”. Unlike my regular presentation this one is entirely slides based which means if you just read the slides, you’ll get the gist of it. Below are all my code examples along with links to further information, example sites and related tutorials to give you some context. Knock yourself out!

Replace Site Title with a Linked Image

This is my number one pet peeve. When people visit a site they intuitively expect the logo or header image to be a link back to the home page, and it should be. When it’s not they (and I) get annoyed. Making your header image link back to your home page is not hard. All you have to do is wrap the header image code in a simple anchor tag that leads back to your root URL and you’re good to go. For simplicity the code looks like this:


<a title="<?php get_bloginfo( 'name' ); ?>" rel="home" href="<?php echo home_url( '/' ); ?>">

… the image code …



For a more in-depth explanation check out the tutorial Twentyten Header Image as Home Button.

Enable WordPress 3 Custom Menus

The WordPress 3 custom menu function is built into the TwentyTen theme and most newer themes, but older themes usually just have hard-coded menus. Adding WP 3 custom menus to a theme is not hard though. It requires a function call in the functions.php file and a template tag in the template file of your choice (usually header.php and/or footer.php). Here’s that code:

In functions.php:


register_nav_menus(
        array(
                'menuName' =>__('Menu Name'),
                ' primary' =>__('Primary Menu'),
                '2ndMenu' =>__('2nd Menu'),
        )
);

Where menuName is the identifying slug for WordPress and Menu Name is the actual displayed name in WordPress Admin.

To display a menu you can either call it based on the slug:


<?php 
        wp_nav_menu(array(
                'theme_location' => 'primary'
        )); 
?>

… or the name defined in the Menus admin area:


<?php 
        wp_nav_menu(array(
                 'name' => 'Menu Name'
        )); 
?>

Menus Outside the Box

Menus don’t have to be regular boring one or two word one-line elements. Because WordPress allows HTML in the Navigation Label you can add more interesting designs like we did on the 12×12 Vancouver Photo Marathon site. On this site we added a simple span tag around the text that displays under the menu heading and then used CSS to change how it displays. Sorry, no code examples – it’s just straight up CSS and out of context it makes no sense.

WordPress 3 Custom Background Images and Colours

The TwentyTen theme introduced a very cool custom background function built right into the admin interface (under Appearance -> Background). This is not a function found in TwentyTen but a core function found in WordPress. That means you can activate it in any theme. All you have to do is call it from the functions.php file:


add_custom_background();

The function injects CSS style code right into the HTML pages which means it’ll override your theme CSS file no matter what. That in turn is why it’ll work on any theme as long as you run WordPress 3.0 or higher.

Adding Featured Image (post-thumbnail) Functionality

Featured images are great, if you know how to use them. They also do way more than just displaying thumbnails (which is why I think the function should be renamed).

To activate the function add the following code to your functions.php file:


add_theme_support( 'post-thumbnails' );

This will add the function to you Admin panel. To display the featured image (in the size you want) in your theme use one of the following functions:


<?php the_post_thumbnail(); ?>

Variations:


<?php the_post_thumbnail('thumbnail'); ?>




Custom Page Templates

Custom page templates allow you to individualize the look of different pages on your site. They can be used to create custom front pages, differentiated legal pages or even custom query pages that pull in posts from multiple categories.

A custom page template is basically a regular page template with a commented out tag at the very top that looks like this:


<?php 

/* Template Name: Whatever */ 

?>

Custom Category Templates

Custom category templates can be used to create differentiated category index sections in a site. Some good examples are the Reeltime Videoworks show reel page and testimonials page and Design Schooled Kids’ press page.

A custom category template can be made in one of two ways. Either create a file with the name category-ID.php where ID is the ID number of the category or category-slug.php where slug is the slug for the category. These files will automatically become the category tempaltes for the defined categories.

Custom Header, Sidebar and Footer

You can also create custom headers, sidebars and footers sort of the same way. You make and call them the same way. For example if you want a custom header you create a new header file called header-custom.php and then call it using the standard get_header() function with a small difference:


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

where ‘custom’ can be anything.

Better Context Links

One of the things that bug me about standard WordPress themes is that they display links to the next and previous posts in the single post view. These links don’t really provide a lot of value. Instead you should be displaying the two latest posts from the current category. So I made a small theme add-in you can dump into your theme for some better context. The add-in adds links to the two latest posts in the current category including the title, publishing date and short description. To install it download the related.php file here (right-click and choose “Save As” – it’s a straight up php file), add it to your theme directory and call it using the following code in your single.php file:


<?php get_template_part('related'); ?>

That’s all you have to do.

Categories
Expression Web Tutorials

Why I Use Expression Web (And Why You Should Too)


As you can see from the sidebar of this blog, my main areas of expertise lie in WordPress and Expression Web. The truth of the matter is for me the two are intrinsically linked: I use Expression Web to make WordPress do my bidding. To that people often ask me “Why?”. “Why do you use Expression Web and not one of the more established web development platforms (i.e. Dreamweaver)?”

To answer this question I wrote an article for the QUE blog entitled Why I Use Expression Web (And Why You Should Too). To go with the article I also created a short video demonstrating the lightning fast CSS abilities of Expression Web. I find that it’s easier to show this technique than try to explain it.

Once you’ve finished watching the video I urge you to jump over to the QUE blog and read my article. I really do think you should start using Expression Web too (and no, I’m not being paid to say that).

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.