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.

Categories
24 Days of WordPress Tutorials

Day 12: Using the All in One SEO Pack plugin

A key question on everyone’s mind when they launch a website is “How do I get people to visit my site from search engines?” It’s a tough question to answer because there are a lot of factors at play, but the overall rule of thumb is to provide accurate and concice descriptions of the page in question in the header of that page. On this 12th Day of WordPress we’ll look at how to make your site and its content more accessible through the use of the very effective All In One SEO Pack plugin.

What does the All In One SEO Pack plugin do?

The All In One SEO Pack plugin is a smart little tool that rewrites the title, description and keyword tags for your posts, pages and index pages. This is important because by default WordPress will grab your post or page title as the title tag and either the first few sentences of your post or your post excerpt as the description. That means if you have a page or post with a nondescript title like “About” and start it off with an image and some generic text or a quote or something, that’s what the search engines will see and index. In addition WordPress will always put your site name first in the title tag, so for example the title tag for this page would be “Design Is Philosophy – The Pink & Yellow Media Blog – Day 12 Using the All In One SEO Pack Plugin. With the All In One SEO Pack the title is instead “Using the All In One SEO Pack Plugin – Design is Philosophy” which makes way more sense and is way more descriptive. And as a bonus, the title tag is also what is displayed at the top of the browser window, in browser tabs and as the titles of bookmarks, so changing them to be more meaningful makes it easier for people to know where they are and what they are looking at. More on that later.

Installing the plugin

The All In One SEO Pack plugin is available from the WrodPress Plugin Directory which means you should be able to install it from right inside WordPress under Plugins -> Add New. If for some reason this option is blocked due to overbearing security measures you can also install it manually by downloading the zipped archive from the directory, unzipping it and uploading it to the plugins folder found under wp-content in your WordPress installation. Once the plugin has been installed, activate it and we can get to work.

Innitial configuration

All In One SEO Pack warningImmediately upon activating All In One SEO you will get a huge red warning at the top of the admin panel (as in the image above). The warning, ominous as it may look, is actually just telling you that you need to configure and enable the plugin before it takes effect. I wish it was a yellow warning instead but who am I to complain, right? To get to the admin page and configure the plugin you can either click the link in the warning or go to Settings -> All In One SEO.

The top of the Options page you’ll see a pile of ads. To get rid of them you have to buy the Pro version (currently on sale for $39). If you’re a blogger or you’re just running one site you can skip this, but if you’re doing industrial sites and the likes it may be a good idea to pay up. Your choice.

Scrolling down you’ll see the actual options for the plugin. And there are a lot of options. When I first started using this plugin a couple of years ago the list was much shorter but even though it may seem like way too much, this new exhaustive list is actually much better. I’m going to go through some of the key options and give you some tips. The rest are pretty slef explanatory and you can also click on each of the option titles to go to a help page with further instructions.

Plugin Status

For the plugin to work the Plugin Status must be set to Enabled. No surprise there. The only reason I mention this is that when there is an update for this plugin (and they come on a monthly basis now it seems) the plugin always gets disabled and you have to go back and enable it again. Quite annoying really.

Home Title

Here you set the title tag for the Home page. This title will override whatever the title is for your home page, whether it is an index page (blog) or a static page. This is especially useful for blogs because without this function set your home page title tag would be the title tag of the most recent post. Very confusing.

Set the Home Title to the name of your site combined with a short description of what it is. For the Everybody Dance site we set it to “Everybody Dance! Vancouver Ballroom Dancing School with Elaine Carson, Dance Coach”.

Home Description

Same as above this function overrides the description of the home page. This is especially important if you are using an index page (blog) as your front page. Make the description an accurate description of what the site is all about, and try to make it short with the most important info at the top.

Home Keywords

There is a lot of debate whether keywords are all that important any more, especially because Google keeps mulling about ditching them alltogether. Keywords used to be the primary focus of SEO but is now way way down on the list. Nevertheless it can’t hurt to insert some accurate keywords (with an emphasis on accurate). Add whatever keywords are appropriate for your home page and move on.

Canonical URLs and Rewrite Titles

Leave these as is unless you have some particular reason to turn them on.

Title Format (multiple)

The next options is a series of title formats for each of the main types of content (post, page, category, archive, tag, search, description, 404, paged). Like I said in the introduction WordPress’ default is to put the site name first and the post or page title second in the title tag. These are the functions that change this order to put the content title first and the site title second. The default settings are good but you can change them around if you want. For instance I tend to change the | to a – because I think it makes more sense semantically. But that’s just me.

SEO for Custom Post Types

Only really matters if you have Custom Post Types in your site, in which case I recommend you get the Pro version of the plugin for further features.

Keywords and other options (multiple)

The next series of options are a bit of a toss up for me. You can change them if you want and it really is something that must be decided on a site-to-site basis. In general I leave them as default because I’m lazy and it works quite well.

Exclude Pages

You can provide a comma separated list of pages you don’t want to be affected by the All In One SEO Pack Plugin. This may sound strange but it makes sense if you are using a plugin that creates a lot of dynamic pages like an advanced calendar or a forum. In general it’s not something you need to worry about.

Additional Post / Page / Home Headers

Very cool feature for nerds like me. This option will add whatever you put in there directly to the header of your site. So if you want to leave an Author META tag you can without having to mess with the theme. I’ve also seen people use this to add custom stylesheet calls (not recommended) and even analytics code (definitely not recommended). Do with it what you like, but remember: Whatever you put in is copied verbatim to the header, so if you insert broken code, you break the page.

Update Options

No real explanation is required here. When you’ve made changes to your settings always remember to click Update Options, otherwise your changes will be lost. And if for whatever reason you want to reset everything, you can by clicking the Reset Settings to Default button. I don’t recommend it.

Using the All In One SEO Pack Plugin

With the plugin installed and configured it’s time to actually use it. The plugin adds a new tab to the edit page for posts and pages and that’s where you will be interacting with it. The Post and Page options differ ever so slightly so I’ll deal with them separately. But before we get started, here’s a tip: When you first open the post or page editor after installing this plugin it will appear towards the very bottom of your page. To make it easier to access (and ensure you actually use it) I recommend moving it up to fit directly under your content area. You do this by simply grabbing the grey bar at the top of the tab and pulling it up to the position you want. WordPress will remember this position for the future.

In Posts

All In One SEO Pack for postsBefore we actually Above you see a screengrab of the All In One SEO Pack tab for this post. As you can see I now have the ability to set a custom title, a custom description and custom keywords for each post from right within the post. And if I so desire, there is also an option to disable the function for this particular page or post.

Here is my general tip: When writing a page or post, give it the normal title you want (like “The tutorial that will change your life” or “About”) and then set the All In One title to something descriptive (like “How to increase the findability of your site” or “About Design Is Philosophy”). That way you get the best of both worlds. As for the description, write a two sentence description of exactly what the post or page is about. This is that little blurb people will see when they find you on Google so make sure it’s good enough to catch their attention right away.

In Pages

All In One SEO pack for pagesPages have two more options added to those of posts: Title Attribute and Menu Label. These interact with the WordPress 3 Menus function meaning if you have a menu item pointing to this particular page (and everything is set up correctly in your theme) you can change the label (the word(s) that show(s) up in the menu) and the title attribute (the screentip that shows up when you hover over the menu item) from right inside the page. This doesn’t always work so be careful. And always alwasy always remember to put a descriptive title attribute on all your menu items, either from the All In One plugin or in the menu settings. This helps Google and your visitors understand where the buttons are pointing.

Wrap up

The All In One SEP Pack should be an integrated part of your writing process, whether you are running a blog or a company website. By making it part of your content creation process you ensure that you serve up the best possible content for search engines and the people who use them and in the process you increase your own findability.

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 11: Creating and Using Custom Page Templates

This will probably be the shortest tutorial in this series, but it is none the less important. On this 11th Day of WordPress I’ll show you how to make a basic custom page template and give you some ideas of how to use them to make your site more interesting.

What is a Custom Page Template?

A custom page template is an alternate template you can use to format your pages. You can add as many custom page templates as you like and you can use them interchangeably. The custom page temlate gives you the ability to create custom layouts for different static pages on your site so they look and behave differently than other portions of your site, most notably the posts.

Custom page templates have many uses. The most common one is probably to create a custom front page that looks different. I use custom page templates to format front pages of sites all the time because they allow me to insert active content that doesn’t fit on other pages. You can see an example of this on the Everybody Dance website.

I also use custom page templates to differentiate between different kinds of page content. For the Frugalbits site I built a series of different page templates. There’s one that looks like the rest of the site used for things like the What is Frugalbits page, there’s one that has just one sidebar with different content for the Legal pages, and yesterday I built a new custom page template with some fancy loop functions to handle the new Frugalbits Cheap Sheet page. Bottom line is the custom page template gives me the ability to customize content in an easy way without having to jump through hoops. And that makes my life easier.

The Custom Page Template in 5 lines of code

Now for the tutorial part: To create a custom page template, find the page.php file in your current theme or parent theme, make a copy, call it something else (like frontPage.php) and open it in your HTML editor.

At the top of the page paste in the following five lines of code:


<?php 

/* Template Name: Whatever */ 

?>

Change “Whatever” to a short descriptive name for your new page template. It can be a name with spaces like “Front page without sidebar”.

Make whatever changes you wanted to make like calling a different sidebar, taking the sidebar out, changing the divs or adding new content, save and upload the file to your theme or child theme folder and WordPress will find it automatically.

Using custom page templates

Custom Page Template in WordPressNow that you have a custom page template it’s time to use it. You can do this from the Edit Page page or using Quick Edit in the page list inside WordPress. You’ll find the Template drop-down menu under Page attributes. From here you simply select the template you want and click Publish or Update and it is automatically applied to your page. And here’s the best part: If you change the page template and find you don’t like it, you can just go and change it back to the default or another template. Nothing is ever final in WordPress.

This should give you an indication of why I like custom page templates so much. Now go out and make your own!

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 10: Creating New Widgetized Areas

When I say “widget” you probably think “sidebar”, right? And you’d be right… well, sort of anyway. In WordPress you’ll normally find widgetized areas in the sidebar of the theme. But there is no reason why widgets can’t be placed elsewhere and used for other things. On this 10th Day of WordPress we’ll look at how to create new widgetized areas in WordPress and how to override the existing widgetized areas in the twentyten theme.

Widgetized areas for just about anything

There are many reasons why you may want to add widgetized areas to your site. You may want to add a seccond column in a sidebar or add a whole new sidebar, you may want to add widgets to your footer or you may want to add a different sidebar alltogether to one of your page or post templates. But widgets and widgetized areas can be used for other things as well. I’ve used them to populate content on the front page, as pop-up messages and as optional spanning banners. A widgetized area is in all honesty just a box controlled from the Appearance -> Widgets area. What you do with that box is up to you.

Setting up a new widgetized area

To set up a new widgetized area you need to do two things: One, define the new widgetized area in your theme’s functions.php file and two, add a call to that widgetized area in one of the template files for your theme. Let’s tackle functions.php first:

More than likely your theme already has widgets activated. You’ll find them by going to your functions.php file and looking for a function called widgets_init() or something to that effect. Within that function you have definitions for each of the widgetized areas. The default use function looks like this:


$args = array(
	'name' => sprintf(__('Sidebar %d'), $i ),
	'id' => 'sidebar-$i',
	'description' => '',
	'before_widget' => '
  • ', 'after_widget' => '
  • ', 'before_title' => '

    ', 'after_title' => '

    ' );

    The variables listed here are more or less optional but as a rule of thumb I recommend leaving them all in. For ease of use it’s a good idea to be quite explicit about what you are building. Say for example I’m adding a widgetized area that will display an ad at the top of my site I would create a new widgetized area using this code:

    
    register_sidebar( array(
    	'name' => ('Header Ad Zone'),
    	'id' => 'headerAdZone',
    	'description' => ('The ad zone that appears at the top of the page'),
    	'before_widget' => '
    ', 'after_widget' => '
    ', ) );

    New Widgetized areaThis produces a the new widgetized area you see to the right.

    The next step is to call this widgetized area from one of your template files. Here we’re going to add a conditional statement that checks whether there is an active widgetized area with content first. That way we’ll avoid trying to activate a widgetized area with nothing in it. The call looks like this:

    
    <?php if ( ! dynamic_sidebar('headerAdZone') ) : ?>
    <?php endif; ?>
    
    

    Here you can choose to insert something between lines 1 and 2 that will be inserted if the widgetized area does not have any widgets in it. The name of the widgetized area (in between the brackets) can be either the name or the ID defined in functions.php

    Changing the widgetized areas in a twentyten child theme

    The twentyten theme has 6 widgetized areas, two in the sidebar and four in the footer. But what if you want to change these or add new ones in your child theme? If you read my earlier tutorial Day 2: Creating a WordPress Child Theme the Smart Way you should already have an idea. Because the widgets_init() function has already been called in the twentyten functions.php file you need to unregister this function and then build a new one yourself. You do this with the following lines of code:

    
    // Remove the default sidebar function
    function remove_twentyten_widgets() {
        remove_action( 'widgets_init', 'twentyten_widgets_init' );
    }
    // Call 'remove_twentyten_widgets' (above) during WP initialization
    add_action('after_setup_theme','remove_twentyten_widgets');
    
    

    Now you can create a new function and create new widgetized areas:

    
    function MY_widgets_init() {
    	register_sidebar( array(
    		'name' => ('Header Ad Zone'),
    		'id' => 'headerAdZone',
    		'description' => ('The ad zone that appears at the top of the page'),
    		'before_widget' => '
    ', 'after_widget' => '
    ', ) ); }

    And finally you need to call the new function:

    
    // Register sidebars by running twentyten_widgets_init() on the widgets_init hook. */
    add_action( 'widgets_init', 'MY_widgets_init' );
    
    

    If you want to keep the existing widgetized areas from twentyten and add on to them simply copy and paste the widgetized areas you want from twentyten’s functions.php over to your child theme functions.php. Then all that’s left is to call the areas from your template files like we did above. Easy as π.

    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 9: Moving Your Comments to Disqus

    disqusOne of the great things about the modern web is that it is no longer a one way conversation but a means of communication between content creators and their viewers. And at the heart of this lies the simple but effective concept of commenting. This feature started with blogs but has now migrated to everything from traditional news media outlets and online merchants to the ultimate extreme version of commenting, also known as “Facebook” where there is nothing but comments. On this 9th Day of WordPress we’ll look at how you can take regular old blog commenting on your site and make it into a more social experience with a service called Disqus.com.

    The perils of open comments

    Allowing visitors to comment on your posts creates a discussion around your content and drives people back to the site. But it also attracts the seething underbelly of the internet: The Spammers, Trolls and good old fashioned nutjobs. WordPress handles commenting quite well, and with the additon of the Akismet plugin you are fairly safe when it comes to spamming and junk content. But sometimes “fairly” just isn’t good enough.

    In October comment moderation on this site became a total nightmare. At the time the site was generating close to 3000 spam comments every day, and even though Akismet was well over 96% effective at catching the junk, at least 40 to 60 spam comments would leak through that I had to go in and delete or tag as spam myself. It became a job in itself and very frustrating for the people who actually want to have a discussion or leave a real comment on the site.

    So I did the unthinkable: I shut down commenting! Well, not completely, but I made it hard to comment on the site to get rid of all the crap. This could be detremental to commenting on the site but it had to be done. After the shut down the first time you comment on this site you get a nasty little message saying “Your comment is awaiting moderation” whereupon I would have to approve the comment for you to be allowed to leave more. An unideal situation if ever there was one as was pointed out in an excellent article by UnMarketing genius Scott Stratten in a blog post yesterday called The Five Words That Kill Your Blog.

    Disqus to the rescue?

    Tratten points out that when you put a wall in front of your commenters so they can’t get the immediate gratification of seeing their words appear on your site, they are going to leave. In other words, the five words “Your comment is awaiting moderation” can be a death sentence where social interaction is concerned. To curb this problem Scott has employed an alternate commenting system from third-party service Disqus.

    As with pretty much everything WordPress there are alternatives to the native commenting system out there, and Disqus is a fast growing one. It plugs into the core of WordPress through a plugin and inserts itself on top of your normal commenting system. The cool thing is that it not only imports all the existing comments on your site when you fist install it but that it leaves a copy of every comment on your site in case you want to drop it later on. In other words nothing is lost and you are not stuck with the service once you start using it.

    The reason Disqus is gaining popularity is twofold: First off it uses OAuth (the open source authorization platform used by Twitter, Facebook and other social outlets) for validation so you can log in using a bunch of different social identities. Secondly Disqus keeps track of all your comments left on different sites in one place so you can log in and see all your interactions with different sites at the same time and monitor whether someone has responded to you etc. On top of that there is a like/dislike system and sharing features. All in all a very nice alternative to the native WordPress commenting feature.

    Installing Disqus on your WordPress site

    That was the ‘why’. Now for the ‘how’. The first thing you need to do is create an account with Disqus: Go to Disqus.com and click Sign Up. On the next page you register your site. It’s pretty straight forward stuff where you leave your site URL, site name and a shortname. You also have to set up the Primary Moderator by creating a Disqus account.

    Disqus site registrationOn page 2 you get a list of options to define. You can do this now or leve it for later. The important thing here is that you can link your comments up to Facebook and Twitter and also allow your visitors to log in through these and other social networks. Now just so you are warned, when you get into the advanced features here like Facebook Connect you have to jump through a whole lot of hoops to get everything to work (if you’re wondering how to get your Facebook API check out this excellent walk-through from shoutmeloud.com). It may not be something you should do right off the bat. Like I said, you can always change things around later.

    Disqus settingsWhen you’ve configured the settings for the site and click Continue you are taken to the core page for your site. Here you can moderate your comments, use the tools, configure and re-configure the settings, add add-ons and most importantly install Disqus on your site.

    Like any serious application Disqus can be installed on a variety of platforms, WordPress included. Clicking the WordPress logo on the Install page takes you to the installation instructions which are pretty straight forward. Even so, here is a step-by-step breakdown.

    Step 1: Add the Disqus Plugin

    Disqus has a plugin called Discus Comment System in the WordPress plugin directory. Go to Plugins -> Add New and search for Disqus Comment System to find, install and activate it just like any other plugin.

    Step 2: Log in

    Upon activation you’ll get a warning at the top of the screen that you need to configure the plugin. You can go directly to Disqus from the warning or click on Comments -> Disqus to do this. First you need to log in to Disqus with the username and password you defined when you signed up. This info is also provided in your step-by-step instruction inside Disqus.com if you’re not sure.

    Step 3: Select a website

    Disqus now asks you to select a website. Most likely you’ll only have one option here but if you are managing several sites you’ll get a list of them at this point. Select the correct site and click Next.

    Step 4: Export existing comments

    This is where the really cool part of Disqus kicks in. Rather than just taking over the commenting system on your blog and dumping all existing comments you have the option of exporting all your existing comments to Disqus at the click of a button. This way all your old comments will still be visible even though the commenting system has been swapped out. When you click the “export comments” link in the text you are taken to the Import/Export section of Advanced Options. Click the Export Comments button and WordPress and Disqus starts talking. Depending on how many comments you already have on your site this may take a good long while. When the export is done you have to wait for Disqus to import the comments as well. You can log in to Disqus and go to Tools and Import/Export to see the progress for yourself. Or watch some paint dry. Whatever fits your fancy.

    Done!

    That’s really all there is to it. Once all your comments are exported they will appear in the new Disqus commenting section. Now all that’s left is for you and your visitors to engage in great conversations with less spam and more social sharing options. Good stuff.

    I’ll be running some pretty heavy experiments with Disqus in the next months and will hopefully be posting some more tutorials on how to style comments and take more control over the application in the neat future. But for now, if you want an alternative to the native WordPress commenting system, give Disqus a go.

    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 8: Styling Author Comments

    Author comment highlighting in WordPressIf you run a WordPress site with comments you have most likely responded to a few comments yourself. But unless people pay attention they won’t necessarily know that you are the author of that post and they may take you for just another commenter. What you need is some styling that visually separates your author comments from the other reader comments. On this 8th Day of WordPress we’ll take a look at the surprisingly easy task of styling author comments for WordPress.

    For simplicity I’m using a twentyten child theme as the example here, but the same principles will carry over to all other themes as long as they use the built in commenting function in WordPress.

    Identifying the author with .bypostauthor

    One of the many great things about WordPress is that as long as you use a well built theme it generates more code and more metadata than you’ll ever need. Comments are no exception. If you open a post with some comments on it and look at the source code you’ll quickly spot lots of seemingly superfluous data that actually offers up hooks for you to connect style code to. Below are two examples of this type of code, the first one from a comment left by a visitor, the second one from a comment left by the post author:

    
    <li class="comment even thread-even depth-1" id="li-comment-1">
    
    
    
    <li class="comment byuser comment-author-mor10 bypostauthor odd alt depth-2" id="li-comment-3">
    
    

    As you can see the second comment carries with it far more information in the form of classes. From the beginning it tells me it’s a comment, it was left by a registered user, that user was me (mor10), and I am also the post author and so on. Styling these classes you can micromanage the appearance of different types of comments in pretty much any way you want. We’re going to focus on the .bypostauthor class but this same technique can be used to target any of the other classes as well.

    Giving the author some style

    Default twentyten commentsIn the twentyten theme all comments are styled the same by default. Even so the development team has prepared style tags for customization of things like odd and even comments as well as the post author. As a result styling comments from a post author as different from other commenters can be as easy as adding a new background colour to the .bypostauthor style like this:

    
    .commentlist .bypostauthor {
    	background-color: #CCCCCC;
    }
    
    

    The result would be what you see below:
    Customized author comment
    Sure, it’s customized, but it lacks that style that makes it attractive. To really make the author comments pop we need to do a bit more.

    Bringing some real style to the author comments

    This is where the lines between the designer and the developer start getting blurred. Creating a great looking style to identify an author comment is as much about coming up with a good look and colour combination as it is finding the correct code to style. For this tutorial I’ve made a bunch of simple changes that add some style to the author comment. Consider these stepping stones on your way to your own custom author style.

    Step 1: Flip the gravatar from left to right

    Looking at the twentyten stylesheet we see that the .avatar style places the image absolutely 4px from the top and 0px from the left. To move it to the right we need to create a new style to override the old one:

    
    .commentlist .bypostauthor .avatar {
    	top: 0px;
    	position: relative;
    	float: right;
    }
    
    

    Step 2: Shift the text to the left

    The position of the text within the comment is defined by the .commentlist li.comment style so to move the text to the left we need to override the left padding. Everything else can be left the way it is:

    
    .commentlist li.bypostauthor {
    	padding: 0 0 0 0;
    }
    
    

    Step 3: Add a nice border with rounded corners

    Now that the layout has changed we can add a border around the comment and give it some nice rounded CSS3 corners. The rounded corners will not work in Internet Explorer until IE9 comes out but even if it doesn’t these borders will still look nice:

    
    .commentlist li.bypostauthor {
    	border: 1px solid #DFDFDF;
    	padding: 15px;
    	margin-bottom: 10px;
    	border-radius: 10px;
    	-moz-border-radius: 10px;
    	-webkit-border-radius: 10px;	
    }
    
    

    The Proverbial tip of the iceberg

    With some simple styling using the .bypostauthor class you can create custom styling for your author comments just like you see in the image at the top of this article. And as you saw by the markup for the comments, you can get even more fancy with it creating custom styles for each individual author if your site has more than one. Now that you know how to do it it’s time to implement custom styling for your author comments on your own site.

    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 7: Brand your social links with the page redirect plugin

    Making WordPress sites work better isn’t always about doing advanced theme hacks and messing around with PHP and CSS code. In many cases it’s just a matter of finding a new or clever use of a plugin or even a function already built in. On this 7th Day of WordPress we’ll take a look at just such a case: Creating brand awareness through social linking with a page redirect plugin.

    Your social links point away from you

    I actually got this idea after seeing a tweet by fellow Vancouverite John Bollwitt. Sadly I didn’t save the tweet at the time, and I can’t remember the exact wording, but I’m sure he won’t mind the paraphrasing. It went something like this: “I don’t understand why companies don’t brand their social links with links such as www.yourdomain.com/facebook. It’s a wasted oportunity.” (John said it better). When I saw the tweet I immediately thought well, it’s because people don’t know how to do that.

    The core of the problem, as pointed out by John, is that when we link to our own presences on social networks like Twitter, Facebook, Flickr and so on, we drive people away from our own sites and towards something else. And even if you manage to snag consistent names and tags throughout like we did for the 12×12 Vancouver Photo Marathon (12x12yvr all around) for all the social networks, you are still left pointing people to links like www.facebook.com/12x12yvr. A better option would be if you could turn it on its head and point them to www.12x12yvr.com/facebook etc. And you can, you just need to know how.

    301 Redirects used in new ways

    The web, as you know, is nothing but a huge list of address pointers pointing in different directions. These links are what binds the web together and there are a lot of different types of links out there. But a link isn’t always a link, and not all links work the same way. A “normal” link is one that points to a specific page or query on a hosted site somewhere. But there are other types of links, of which the 301 link (or more specifically 301 redirect) is of importance to us. The 301 redirect is a permanent redirect that takes the browser query and jumps it to a different defined link immediately. So for example when you type in “http://www.12x12yvr.com/twitter” in your address bar, the browser immediately jumps to “http://www.twitter.com/12x12yvr” without causing a fuss. If you were to do this using a more basic HTML redirect within a page the browser might stop it from happening.

    These redirects, the 301 being permanent while the 302 and 307 are temporary, are designed to do things like direct people visiting old links to the correct places on new sites. But there is no reason they can’t be used for other purposes, and with the entry of social networks galore these redirects are coming to the forefront as an important tool.

    Question is how do you do this in WordPress. After all, when you make a page in WordPress with a specific title like “Twitter” and you have your permalinks in order, the browser will land on that page. So how do we solve the problem?

    Quick Page/Post Redirect to the rescue

    I hate how it sounds, but there’s a plugin for that, called Quick Page / Post Redirect Plugin. This plugin integrates with WordPress to allow you to create custom 301, 302 and 307 redirects for all your pages and posts. As a result you can personalize and brand the online experience even when people leave your site. Take the 12×12 Twitter link as an example:

    URL redirect in WordPressAfter installing the plugin I simply created a new Page called “Twitter” and scrolled down until I found the Quick Page/Post Redirect tab. In the tab (as seen above) you can set each post or page URL to be an active redirect, tell the browser to open the redirect in a new window, add nofollow to the link so search engines don’t start indexing all of Twitter or Facebook on your behalf and decide whether or not you want to show the Redirect URL in the link.

    Once you’ve decided on your settings you can insert your Redirect URL in the field below. This can be anything from a relative or root-relative link, a query or an absolute link – your choice. Once that’s defined all you have left to do is set the type of redirect. By default it’s set to 302 which is a temporary redirect, but for social links to Twitter, Facebook and the likes the correct setting here is 301 – permanent.

    With the settings in order, the URL defined and the redirect set to 301, all that’s left is to publish the page and with that you have your own customized social media link ready for advertisement. Simple, easy and incredibly effective.

    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 6: Pretty Permalinks and How To Keep Old Links Alive

    Have you ever looked at the URLs of your posts and thought “Hm, that might be a bit hard to remember” or even “I wonder what all that stuff means”? If that sounds familiar it’s high time you learned about permalinks and how to make them “pretty”. On this Sixth Day of WordPress we’ll take a look at how to get WordPress to use so-called “pretty” permalinks and also how to change the permalinks of existing WordPress sites without losing old links pointing to the site in the process.

    Note that though this is fairly basic stuff that should work fine on most WordPress installations and hosts, I have encountered one case in which messing with the permalink structure had truly horrific site-destroying consequences. The following comes with no warranties and I take no responsibility if something goes wrong when you follow these instructions. That said I do what is described below on all the sites I work with and apart from that one very strange case on a very strange server I have never had any issues.

    Pretty Permalinks: What they are and why they matter

    To understand pretty permalinks and how to make good use of them you first need to understand what they are and how they work. If you already know this you can skip this section and move on to the next one. If not, I’ll try to be concise and educational.

    When you create a post or page in WordPress you are actually just creating a database entry equivalent to one row in a spreadsheet. Each post or page is assigned and identifying number so it can be tracked down and called by WordPress at any time. As an example this post has been assigned the number 1040. To call the content from one such entry, all you have to do is tell WordPress to display the content of row 1040 like this: http://www.designisphilosophy.com/?p=1040. This is called a query and it is at the core of WordPress’ functionality.

    The problem of course is that whereas the server might find it very easy to deal with each post or page as a number, your visitors and search engines can’t really make heads or tails of it. They’d much rather have a proper description of the content of a particular post. This is where the pretty permalinks come in. By setting up a permalink structure for your WordPress site you tell WordPress and the server to assign new semantic (meaningful) URLs to each post and page – usually based on the title. So instead of that weird URL above the permalink URL for this page becomes http://www.designisphilosophy.com/24-days-of-wordpress/pretty-permalinks-and-how-to-keep-old-links-alive/. Not only is this new URL written in English, but it gives a clear description of the post: It belongs to 24 Days of WordPress and it has something to do with permalinks. And that’s what we want.

    Setting up permalinks in WordPress

    By default WordPress uses the numbering scheme for all your content. This is not what you want unless your site will only be read by computers. Which I guess could happen. Fortunately changing the permalink structure for WordPress is a 10 second process:

    1. Go to Settings -> Permalinks
    2. Click the “Custom Structure” radio button
    3. Enter the following strip of code: /%category%/%postname%/
    4. Click Save Changes

    Setting up WordPress permalinksIf your server allows WordPress to write to the .htaccess file this is all you have to do and your posts will now be listed as http://www.yourdomain.com/category/postname while your pages will be listed as http://www.yourdomain.com/pageparent/pagename. Done and done.

    .htaccess trouble

    In some cases the server will not let WordPress write to a file called .htaccess. If so you have to do some manual labour to get everything to work. Good thing is WordPress does the work for you – you just have to copy and paste some code.

    If when you followed the 4 steps above WordPress runs into trouble it’ll give you a warning at the bottom of the page that looks something like this:

    WordPress permalinks .htaccess problemAll you have to do now is copy the code in the box (may be different from what you see above), paste it into the .htaccess file and push it back up to your server. Here’s a more thorough rundown step by step:

    1. Log in to the root folder of your WordPress installation through FTP
    2. In the root instalation you should find a file called “.htaccess”. If so copy it to somewhere on your desktop and make a backup copy called “.htaccessOLD” just in case something goes wrong.
    3. Open .htaccess in your text editor.
    4. If there is no .htaccess file in your root folder, open your text editor and create a file named “.htaccess”. Note there is no prefix here and the file has no file type. If you save it as “.htaccess.txt” for example it will not work.
    5. Go to the Permalinks page in your WordPress installation, find the code as illustrated above and copy the whole bulk of code.
    6. Go to .htaccess and paste the code in anywhere.
    7. Save .htaccess and use your FTP client to put it back into the root folder of your WordPress installation.

    Now when you reload your WordPress site it should have pretty permalinks. If it doesn’t you missed a step somewhere. If everything explodes or nothing loads, go back through FTP, remove the .htaccess file, make a copy of your backup file, rename it “.htaccess” overwriting your new broken version and push .htaccess back up to your site through FTP. This should restore everything.

    Configuring permalinks on a post-by-post basis

    Now that you have your pretty permalinks properly configured you can start customizing them. When you create a new post or page and click either Save Draft or Publish, WordPress generates a permalink for you. If you used my permalink structure above the post will get a URL based on the category and post name (or in case of a page the page parent (if any) and the page name). If it’s a post with multiple categories WordPress will pick the first category alphabetically and use that one so if you want a specific category pick that one first, save the post as a draft and then add additional categories.

    Changing a post permalink in WordPressOnce a permalink has been established, you can change the postname portion of it. You do this by clicking the Edit button that appears directly next to the permalink (which is displayed directly under the post title) and typing in a new title. Keep in mind on the web only standard English letters work and you can’t have any spaces so separate your words with dashes. When you’re satisfied click OK and the new permalink is applied.

    WordPress does a pretty good job at defining these permalinks for you but you may want to edit them. For example this post is has the words “Day 6” at the beginning of the title, but since I don’t think people are going to search for “Day 6” hoping to find an article on WordPress permalinks I’ve taken it out.

    Changing permalinks without killing old links

    “But” you may say “my site has been up for years using the old crappy numbering system and thousands of sites link to me already. If I change the permalink structure on my site, all those links will point nowhere. That can’t be good.” And you will be right. If you have an existing site with an old permalink structure – whether it be the default or some strange structure you or your web developer came up with a couple of years ago – and you want to change it you have to insert safeguards that people who visit your posts and pages using the old structure won’t be led astray.

    Fortunately, like with most things WordPress, there’s a plugin for that. And it’s called Dean’s Permalink Migration plugin (for a full breakdown check out Dean’s site).

    Dean's Permalinks Migration pluginThis plugin works on a very simple principle: You provide the old permalink structure for your site and it will redirect anyone using that old structure to the new permalink locations. Once you have the plugin installed (it’s available through the WordPress Plugin Directory and can be installed from within WordPress) and activated, a new option appears under Settings called “PermalinksMigration”. To use the function simply click this option, enter the old permalink structure in the field and click Update Options. Can’t get much simpler than that.

    Now if for some strange reason you have multiple different permalink structures you need to redirect there are other more heavyweight plugins available, but I find that in most cases the simplest option is the best one and this is as simple and straight forward as it gets.

    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 5: Adding custom WordPress 3 menus to your theme

    In Day 4: Using WordPress 3 Custom Menus I showed you how to get the most out of the custom menu function introduced with WordPress 3. In this Fifth Day of WordPress I’m going to take that a step further and show you how to add new Theme Locations for your menus. This procedure can be used to add new menus to existing themes like twentyten and it can be used to add the WordPress 3 custom menu functionality to old themes that don’t have it already installed. I’ll show you how to add the menu function, how to add the menus to your theme files and also talk a bit about the different variables available when you create custom menus. Lots of ground to cover here so let’s get started.

    Setting up the custom menu function

    To get custom menus to work within your theme you first have to add the function to your theme. That’s done in the functions.php file. The basic function you need to add looks like this:

    
    <?php 
    register_nav_menus( array(
    	'Menu1' => 'Menu 1 Name',
    	'Menu2' => 'Menu 2 Name',
    	'Menu3' => 'Menu 3 Name',
    ) );
    ?>
    
    

    The first part of the array variable (Menu1, Menu2, Menu3) are the elements used to call the menu from the template files. The second part (Menu 1 Name etc) is the menu name as it will appear inside the Menus function in WordPress.

    If you’re working with a theme that doesn’t have the WordPress 3 menu function already installed, or if you want to add more menus, you simply copy the code above, paste it into functions.php and customize it to your liking. If you are working with a twentyten child theme you need to unplug the twentyten menu setup first. I already covered how to do this in Day 2: Creating a WordPress Child Theme the Smart Way but it doesn’t hurt to repeat it. Simply create a functions.php file in your child theme folder, copy and paste this block of code in and you’re good to go:

    
    <?php 
    
    // Remove the default 'register_nav_menus' function
    function remove_register_nav_menus() {
        remove_action( 'twentyten_setup', 'register_nav_menus' );
    }
     
    // Call 'remove_register_nav_menus' (above) during WP initialization
    add_action('after_setup_theme','remove_register_nav_menus');
     
    // Register new 'register_nav_menus' function by running 'register_nav_menus' on the 'twentyten_setup' hook. */
    add_action( 'twentyten_setup', 'register_nav_menus' );
     
    // This child theme uses wp_nav_menu() in two locations.
    register_nav_menus( array(
    	'primary' => 'Header Menu',
    	'secondary' => 'Footer Menu',
    ) );
    
    ?>
    

    In this case I’ve created two menus: Header Menu and Footer Menu. And when you

    Adding a new menu to a theme template

    New WordPress 3 menuWhen you’ve added the code above to your functions.php file you’ll find a new Theme Location option in the Menus area in the WordPress admin panel. But to get the menu to display somewhere in your theme you have to do some more work. By default twentyten has the primary Header Menu installed so we don’t have to worry about that as long as we set the variable name to “primary”. As for the Footer Menu we have to add that one manually into the theme files. Since we want it to appear in the footer we create a copy of the footer.php file from the twentyten folder in the child theme folder. This child theme footer.php file will now override twentyten’s footer.php file.

    The next step is to add the template tag to call the menu. This is where things get interesting. You can call the menu in two different ways; either based on the name as set by the functions.php file or based on the menu name as defined by the user. If you pick the first (and safest) option this is the code you want to use:

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

    If you want to use the second option for some reason (for example if you want to add an optional menu to a free theme) you use this code:

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

    It’s all pretty self explanatory, but here is a concrete example: If you want to call the footer menu we created above you insert the following block of code into the new footer.php file:

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

    This adds the menu as an unordered list in the footer. Now all that’s left is to style it – but that’s a whole different tutorial.

    More options than you’ll ever need

    If you go to the twentyten theme and look in header.php you’ll find this block of code on line 85:

    
    <?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?>
    
    

    You’ll recognize most of it but there’s more stuff here than I told you to use before. That’s because the wp_nav_menu function comes with an insane ammount of variable options to customize the output. In the case of the twentyten header menu the code says that the div container inside which the menu is wrapped should have a class named “menu-header” attached. This is for styling purposes so you can use different classes or IDs to target different menus. There are tons of other options as well, some more useful than others and you can read all about them in the WordPress Codex function reference page. I recommend you read the page and experiment with the output. It can be quite interesting to see what comes out and the variables open a lot of posibilities for customization. For your reference I rarely use anything more advanced than what you see in the twentyten example above.

    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 4: Using WordPress 3 Custom Menus

    In this Fourth Day of WordPress let’s take a closer look at the new custom Menus function that was introduced with WordPress 3.0. You may already be aware of this function, and you may even have used it before, but it has some pretty nifty uses you may not be aware of, so please read on.

    Basic menu creation

    Assuming you’re working with a theme that supports WordPress 3 menus, actually making a menu is very easy. I’m using twentyten as an example here but it’s the same for any theme with this function installed. If you haven’t created a custom menu yet WordPress will insert a menu consisting of a Home button plus a list of all your top-level pages. Any children of these pages will be listed in the drop-down elements.

    WordPress 3 MenusTo get to the menu option go to Appearance -> Menus. Here you will see the standard Menu dashboard. Opening it for the first time there are no menus defined and it is empty. To start off you need to insert a Menu Name and click the Create Menu button. Now you have a custom menu you can work with.

    WordPress 3 MenusAt the top left is a box labeled Theme Locations. Depending on what theme you use there can be one or several locations listed here. Below each location is a drop-down box where you can pick what menu goes in that alocation. For twentyten there is one theme location and that’s where you want your custom menu to appear so select it and click Save.

    Adding new buttons to the WordPress 3 menuNow it’s time to add some menu elements. You can add one of three types of elements: Custom lins (pointing to anywhere within your site or on the web), Pages and Categories. This is what makes the menu feature so powerful: You can now create a custom menu with a mix of different types of links. In the past this required either a hard-coded menu, a pile of theme hacks that were quite complicated or a dedicated plugin. No more of that nonsense. To add menu items simply select them and click Add To Menu and they appear. Note that if you want a dedicated Home button select the View All tab under Pages and you’ll be able to select it from the list.

    Moving WordPress 3 menu itemsNow comes the fun part: With menu items added to your custom menu, you can move them around and organize them in hierarchies simply by clicking and dragging them around (see image above). This means you can modify your menu on the fly to fit your own preferences or those of your visitors. In short, your menus are not static any more but dynamic entities that can be changed and configured at any time.

    When you click the Save Menu button and go to your site you’ll see that your new menu has replaced the default one. Very neat. But that’s just the beginning.

    Menu item customization

    Each of your menu items can be customized in some useful and surprising ways. I’ll give you some examples.

    WordPress 3 menu item configurationFor each menu item you can make in-menu changes to the Navigation Label (the actual text that appears in the menu) and the Title Attribute (the screentip that pops up when people hover over it). For the custom link menu items you can also change the URL. To access these options simply click the little down arrow on the right side of each item tab. As a rule of thumb every menu item should have a defined and descriptive Title Attribute. This is both for people who are accessing your site using a text-to-speech browser, text-only browsers and also for your primary blind reader Google. When you make changes to the menu items remember to click the Save Menu button in the top right corner, otherwise the changes are not saved. From within the menu item configuration area you can also Remove any menu item from this menu. Doing this does not delete the content, just removes the menu item.

    Fancy Menus With HTML

    Fancy WordPress 3 menus with HTMLThat’s all well and good, but I’m pretty sure if you’ve played around with these menus at all you already knew all of this. So here’s something you most likely didn’t know: The Navigation Label field can receive HTML code! The image above shows the header menu we built for the 12×12 Vancouver Photo Marathon website. As you can see each of the menu items contains more than just one or two words, and the content within each item is split into two separate styles: an all-caps main title and an all lowercase description. To achieve this we simply inserted some HTML into the Navigation Label field of the menu items as you see in the image below.HTML in WordPress 3 menusNow just so we’re clear: Getting this to work requires quite a bit of style code – it’s not automatic.

    I’ve tested this extensively, and the menu items will simply feed out pretty much any HTML you stuff the Navigation Label field with. That means you can create some pretty ridiculous conflicts if you’re not careful. For example, you could insert an <a href> tag in the Navigation Label field that points somewhere entirely different than the menu item itself. This can produce some rather unfortunate results. You can also stuff it with active JS and even embed and iframe codes. I do not recommend it. Sticking with simple <span> tags and other stylistic elements is safe.

    Custom Menu Widget

    Custom Menu WidgetIf you have already filled out all your theme menu areas or you want to create an additional menu somewhere else you can use the Custom Menu widget. This widget allows you to place any of the menus you create within the Menus area in any widgetized area. That means you can add a custom menu to your sidebar or any other widgetized box, for example in the footer. Twentyten comes with a huge pile of widgetized areas you can populate with custom menus.

    To use the Custom Menu Widget to to Appearance -> Widgets, locate the Custom Menu widget and drag-and-drop it to your desired widgetized area. Once there you can give the custom menu a title (if you don’t give it a title it will appear without one) and select which of your custom menus to display.

    Using the custom menu widget in conjunction with the theme menus you can create a whole variety of custom navigation scenarios depending on where the user lands on your site. This shows just how useful and revolutionary the custom menu function in WordPress 3 really is. Now that you know, go out and make some cool menus of your own!

    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 3: Twentyten header image as home button

    On this Third Day of WordPress I’m going to cover something a lot of people ask about and something that is also a bit of a pet peeve for me: Making the header image of the twentyten theme into a Home link and get rid of the site title and description in the process. I’ve covered the topic of using an image as your home link in passing in previous posts, last of which was Simple Yet Powerful WordPress Hacks, but here I’ll go into a bit more detail and show you how to do this specifically in the twentyten theme using a child theme of your construction. Coincidentally this same example is covered in my Lynda.com video series WordPress 3.0 Essential Training.

    Image as header Home link – the basics

    Let’s cover the basics first. The purpose of this tutorial is to show you how to remove the text version of your site title and replace it with an image that still functions as a home link. We’ll attach the same attributes as the text title and let WordPress define things like where it points and what the alternate title is etc. automatically. The reason you want to do this is so that you can use your own logo as the home link rather than a block of text. I say this is a pet peeve of mine because I find a lot of sites that have a logo that is not a home link and when I do I sit there clicking on it wanting to go to the front page but can’t. This tutorial will solve that problem for you permanently.

    First let’s just take a quick look at the code ignoring the twentyten theme. By default you’ll find that most themes have a line of code in header.php that looks something like this:

    
    <h1 id="site-title"><a href="" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
    
    

    This is the code that grabs the defined title of the site as set under Settings -> General and displays it on the front page. To replace this with an image we can simply comment out the above line and paste this one in instead:

    
    <div id="blog-title"><a href="<?php echo get_bloginfo('url') ?>/" title="<?php get_bloginfo('name') ?>" rel="home"><img alt="<?php get_bloginfo('name') ?>" src="<?php echo get_bloginfo('template_url') ?>/imageFolder/imageFile.type" /></a></div>
    
    

    and place the desired image in themes/yourtheme/imageFolder/image.type. This magically replaces the text with an image, makes the image a home link and even grabs the site title and inserts it in both the link title attribute and the image alt attribute.

    Making the custom header image in twentyten into a home button

    We can apply this same process to the twentyten theme, but we need to make some changes because the header image is generated dynamically from within WordPress (under Appearance -> Header). First off you need to make a child theme. That was thoroughly described in Day 2: Creating a WordPress Child Theme the smart way. Next copy the header.php file from the twentyten folder and paste it into your child theme folder. Now we can start mucking around with the code.

    Since the theme already has a header image we need to find it. In the header.php file it’s found on lines 68 to 78 and looks like this:

    
    <?php
    	// Check if this is a post or page, if it has a thumbnail, and if it's a big one
    	if ( is_singular() &&
    		has_post_thumbnail( $post->ID ) &&
    		( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'post-thumbnail' ) ) &&
    		$image[1] >= HEADER_IMAGE_WIDTH ) :
    		// Houston, we have a new header image!
    		echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
    	else : ?>
    		<img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
    <?php endif; ?>
    
    

    To make this into a home link we simply have to wrap this line of code in a link making sure to use the correct template tags to grab the home link and the site title. The code is

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

    and it goes at the top and bottom like this:

    
    <a href="<?php echo get_bloginfo('url') ?>/" title="<?php get_bloginfo('name') ?>" rel="home">
    	<?php
    	// Check if this is a post or page, if it has a thumbnail, and if it's a big one
    	if ( is_singular() &&
    		has_post_thumbnail( $post->ID ) &&
    		( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'post-thumbnail' ) ) &&
    		$image[1] >= HEADER_IMAGE_WIDTH ) :
    		// Houston, we have a new header image!
    		echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
    	else : ?>
    		<img src="" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
    	<?php endif; ?>
    </a>
    
    

    Save that and deploy the child theme on your WordPress site and you’ll see the image is now a clickable link that points back to your home page.

    Getting rid of the site title and description

    Now that we have a clickable header image that we can replace with an image with a logo and a tagline etc, we don’t need the site title and description any more. So we can take it out. Fortunately that’s pretty damn easy to do – just delete a few lines and you’re done. But wait. I have a better option (and it’s one that I use all the time): Rather than deleting the code, use HTML comments to make it invisible to the browser. This serves two purposes: First of all, if you make a mistake you don’t have to reconstruct the code – just remove the comments and you’re good to go. But more importantly, commenting out the code means you can always come back to it later if you change your mind. It’s a safe way of making alterations in your WordPress theme and is a best-practice model for web development in general.

    The code in question is found on lines 60 to 66:

    
    <?php $heading_tag = ( is_home() || is_front_page() ) ? 'h1' : 'div'; ?>
    <<?php echo $heading_tag; ?> id="site-title">
    	<span>
    		<a href="" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a>
    	</span>
    </lt;?php echo $heading_tag; ?>>
    <div id="site-description"><?php bloginfo( 'description' ); ?></div>
    
    

    The 5 first lines contain the site title, the last one contains the site description. The reason for all the convoluted code in the site title is that the theme detects whether the visitor is on the front page or not and changes the type of tag attached to the title accordingly: If the visitor is on the front page the title is given the h1 tag and is considered to be the de-facto header of the site. If the visitor lands on a different page the title is wrapped in a generic div tag and the page header is assigned h1 status. This is for SEO purposes. More on that at the very end of this piece.

    To get rid of the site title and description simply wrap the above code in HTML comments like this:

    
    <!--
    <?php $heading_tag = ( is_home() || is_front_page() ) ? 'h1' : 'div'; ?>
    <<?php echo $heading_tag; ?> id="site-title">
    	<span>
    		<a href="&t;?php echo home_url( '/' ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a>
    	</span>
    </<?php echo $heading_tag; ?>>
    <div id="site-description"><?php bloginfo( 'description' ); ?></div>
    -->
    
    

    Shockingly easy isn’t it? Now all that’s left is for you to create a custom header image with your logo or site name and you’re set to go. As a bonus twentyten allows you to assign custom header images to each of your pages through the Featured Image function, so you can do further customization of your site that way. If you’re interested in seeing how far that can take you check out my Lynda.com video series WordPress 3.0 Essential Training where I explain it in greater detail.

    What about SEO and all that stuff?

    Now a bunch of you will cry foul and say “Oh, but Morten… this means the front page has no H1 tag and furthermore that there is no #site-title ID anywhere. That will confuse search engines and ruin the site SEO”. To that I say: 1. That’s rubbish. If a page doesn’t have an H1 tag search engines automatically jump to H2. It makes no difference. 2. If you’re absolutely insisting on having a H1 in here, you can do this the a-bit-more-complicated way by adding an H1 page title to the header image and use CSS to hide it by pushing it to the side. That requires a whole new tutorial but it’s not all that hard. Bottom line is it’s not necessary. If you’re worried about SEO on your site, just get the All In One SEO plugin and most of your problems will be solved.

    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.