Custom WordPress sidebars using is_child

A common request by designers is to set up a website with a main top navigation and secondary sub nav based on the page you are on. An example of this can be found on the Out of Chaos website where once you leave the home page, the sidebar displays the different pages belonging to that section.

This can easily by done by updating your sidebar template using conditionals.
For example:

<ul>
<?php if(is_page(2) || is_child(2)) {
  wp_list_pages('child_of=2&depth=1&title_li=');
 } elseif (is_page(3) || is_child(3)) {
  wp_list_pages('child_of=3&depth=1&title_li=');
 } elseif (is_page(4) || is_child(4)) {
  wp_list_pages('child_of=4&depth=1&title_li=');
 } else (!is_page()) {
  wp_list_categories('title_li=');
}?>
</ul>

Where the # refer to the page id of your page.

Now if you run this code above, you’ll most likely get an error. This is because the is_child() function is NOT part of WordPress core. In order for the code to work we must use c.bavota’s is_child() function.

function is_child($page_id_or_slug) { 
 global $post; 
  if(!is_int($page_id_or_slug)) {
   $page = get_page_by_path($page_id_or_slug);
   $page_id_or_slug = $page->ID;
  } 
  if(is_page() && $post->post_parent == $page_id_or_slug ) {
   return true;
   } else { 
    return false; 
 }
}

Once the above code snippet is added to your function file, you can easily add as many sub navigation menus as you need.

Protecting your email address from spam bots

With all the great things that came along with the Internet, spam is probably the worse downside. No one is immune to it and spam is simply part of everyday life. There are of course, a few things you can do to protect yourself.

Keeping your email address private, i.e. never putting it up anywhere is by far the best way to avoid spam, but that’s not always possible.

One way to make it harder for spam bots to harvest your email address is by encoding it. Encoding is simply the process of changing the email into code making it harder to robots to recognize.

A new WordPress plugin was released at the end of 2011 which does just that. Once installed and activated, the email address encoder plugin turns email addresses and mailto links into decimal and hexadecimal entities thus protecting them. The plugin works on email addresses throughout your WordPress site including comments.

Setting up a WordPress site properly

I’ve been WordPress teaching for a few years now and I’ve shown many students what steps to take when setting up a site, but it seems that once out of the classroom, these steps are forgotten. I’ve also noticed this with folks asking for help on the WordPress forum. So many designers try to design their WordPress theme without any content and ensuring their setup is right. These first initial steps aren’t that difficult and will ensure that nothing is forgotten when it’s time to launch. So here is the process I follow with every single wordPress build.

  1. Install WordPress and log on.
  2. Navigate to my Post section and rename the Uncategorized category to something more sensible. More often than not, I change it to News. If I know what other categories will be needed, I insert them here as well.
  3. If I have blog content from the client (99% of the time I don’t), I insert it here. If I don’t have any blog posts content, I like to install the WP Example Content plugin which generates 5 posts and pages. 
  4. Unlike blog posts, most clients do provide page content. So at this stage I would create the various pages and set up my menu via the Appearance > Menus.
  5. Next I’ll navigate to my settings and ensure that under the general setting,  the full site title and tagline are inserted and I’ll change the timezone to the clients’ timezone.
  6. Under Settings >  Writing I make sure that the appropriate category is selected as the default post category.
  7. Under Settings > Reading I change the front page display to a static page. I usually select Home for my home page and Blog for my post. Again for me, 99% of the time, my clients want a site with a front page and blog posts appearing as a sub page.
  8. Next we have the comments which are under Settings > discussion I normally don’t change much in here except when clients do not want comments at all.
  9. The Media section is next and again, I normally leave the default as is.
  10. During the build of a site, I make sure to check the second radio button on the privacy settings and block search engines.
  11. Finally the last step and probably the most important one is the permalinks. I usually select the second option. I’m no SEO Guru and really don’t think that one permalink over another is going to make That much difference. I used to opt for custom permalinks and set them to /%category%/%postname%/ but then I read Chris’s post and I stopped that.(I know he didn’t say to stop using /%category%/%postname%/ but still, if that custom permalink is better, wouldn’t WordPress have made it an option? Those folks are smart, so I prefer to go with one of their choices. :-D)
    Setting up the permalinks at the beginning of a project can also save you a lot of grief from your client. If you discover that their server doesn’t support mod_rewrite, then finding this out before the launch will give you plenty of time to find an alternative.

Once I have taken care of these 11 steps, then I start building the theme. I’ve seen many designers get caught out when launching a site realizing that they didn’t style the blockquotes or the list items. Ensuring that you have content, even dummy content, during the build will help you release a better theme for your client.

Favourite WordPress conditional tags

Understanding conditionals is an absolute must in creating unique WordPress sites. Like its name suggests the conditional tag allows you to display content depending on a specific condition.

The best place to start when learning how conditionals can be used is with page settings.

For example if you wanted to post a message of your home page or display a specific image, the following code would be added to your template file:

<?php if(is_front_page()) {?>
	<p>This is our front page so we will do this.</p>
	<?php } else {?>
	<p>We're no longer on the front page, so we will do that instead.</p>
<?php } ?>

Display different content on your sidebar

Conditional tags also allow you to dress up your sidebar differently depending on where you are on your site. I find myself building lots of websites for clients who do not wish to modify their first level of navigation, but do have the need to modify subpages. Thus with the parent page in place, I use the following code in my sidebar to create the sidebar navigation for each section.

<ul>
<?php if(is_page(2) || $post->post_parent==2) {
	wp_list_pages('sort_column=menu_order&amp;child_of=2&amp;depth=1&amp;title_li=');
	} elseif (is_page(3) || $post->post_parent==3) {
	wp_list_pages('sort_column=menu_order&amp;child_of=3&amp;depth=1&amp;title_li=');
	} elseif (is_page(4) || $post->post_parent==4) {
	wp_list_pages('sort_column=menu_order&amp;child_of=4&amp;depth=1&amp;title_li=');
	} elseif (!is_page()) {
	wp_list_categories('title_li=');
	}?>
</ul>

The page(#) correspond to the page ID. You could also use the slug if you prefer, but don’t forget to use single quotes.

Check to see if custom field exists

Conditional tags can also be used to check for things other than being a certain page. Testing to see if a custom field exist for example can be handy:

<?php while (have_posts()) : the_post();
	$link=get_post_meta($post->ID, 'link', true);
		if($link != '') {
 		echo '<a href="'.$link.'">';
 		echo the_post_thumbnail().'</a>';
		}else {
 		the_post_thumbnail();
		}
the_content();
endwhile; ?>

A similar example would be to check to see if a featured image has been uploaded and if not display a default one.

<?php if(has_post_thumbnail()) {
 	the_post_thumbnail();
	} else {?>
 	<img src="<?php bloginfo('template_directory');?>/images/banner.gif" alt="">
<?php }?>

As you can see conditional tags are very handy. The examples above are some of my most used code snippets. Do you have any favourites?

Fixes to WordPress 3.1 admin bar bug

WordPress 3.1 was released a couple of days ago and along with it the new admin tool bar. Once you’ve upgraded and logged in, you’ll notice it at the top of your site.

The Admin Bar provides quick access to edit or add pages and posts, moderate comments, etc. I spent a good part of the day yesterday upgrading 40+ WordPress sites which I host for clients. These upgrades proved fast and simple and I only encountered two glitches.

Missing Admin Bar

The first glitch encountered was by the absence of the admin bar altogether. I could see a space at the top of the site where the admin should be, but nothing. I posted my conundrum on twitter and got an answer from Andrea_r 3 seconds later.

Checking the theme files, I discovered that in order for the bar to show up, the function <?php wp_footer();?> must be present. Once incorporated, the admin bar showed up.

Messed up Admin Bar

The second glitch took me much longer to figure out. I was also convinced that the error was mine and in my theme and so refused to ask twitter. (Stubborn much?)

Upon upgrade, I noticed that the styling of the admin bar was all messed up. I did the usual testing by deactivating all of the plugins and switching themes. All of these tests pointed to my theme. Originally built in 2005 this bug was the perfect opportunity to go through it anyway and sort this bug out and see what other messy code was in there.

So I proceeded to go through all of the files to see what was causing the glitch. The problem was again found in the footer, but this time the encrypted email I was using was causing the error.


<a href="ma&#105;&#108;to:i&#110;&#102;o&#64;&#116;&#97;k&#117; etc... 

Removing this bit fixed the issue. Yay!

Display random image in sidebar using Custom Post Types

I recently created a website for Vancouver’s newest Tourist Attraction, the Pink Bus Tour. Later this summer, Vancouver residents will witness the Pink Bus carrying tourists around the city. A big part of the website was to showcase the highlights of the city. These highlights are simply pages within the CMS and my goal was to randomly display a “highlight” in the sidebar.

The highlights in the sidebar were easy to make. They simply consist of an image and a link. The problem was how to pull an image and link at random AND make it easy for the staff at Vancouver Pink Bus to add new images and links once available.

Using a Custom Post Type seemed to be the easiest way to go about this. To create the custom post type, I added the following to my functions.php file:

// Custom Highlight in sidebar
   add_action('init', 'create_highlight');
     function create_highlight() {
       $highlight_args = array(
          'labels' => array(
           'name' => __( 'Highlights' ),
           'singular_name' => __( 'Highlight' ),
           'add_new' => __( 'Add New Item' ),
           'add_new_item' => __( 'Add New Highlight Item' ),
           'edit_item' => __( 'Edit Highlight Item' ),
           'new_item' => __( 'Add New Highlight Item' ),
           'view_item' => __( 'View Item' ),
           'search_items' => __( 'Search Highlight' ),
           'not_found' => __( 'No highlight items found' ),
           'not_found_in_trash' => __( 'No highlight items found in trash' )
         ),
       'public' => true,
       'show_ui' => true,
       'capability_type' => 'post',  
       'hierarchical' => false,
       'rewrite' => true,
       'menu_position' => 20,
       'supports' => array('title', 'editor')
     );
  register_post_type('highlight',$highlight_args);
}
add_filter("manage_edit-highlight_columns", "highlight_edit_columns");
add_action("manage_posts_custom_column",  "highlight_columns_display");

function highlight_edit_columns($highlight_columns){
   $highlight_columns = array(
      "cb" => "<input type=\"checkbox\" />",
      "title" => "Title",
   );
  return $highlight_columns;
}

Once this code in place, the highlights were ready to be populated. Now when a new sidebar image is needed, the folks at Vancouver Pink Bus simply upload a new polaroid image, link it to the page (made so much easier now WordPress 3.1 internal linking feature) and that’s it.

The final step is to display, at random, one of these custom post types. This was done by adding the following to my sidebar:

<h3>Highlights Include</h3>
<?php
 $loop = new WP_Query(array(
  'post_type' => 'highlight', 
  'posts_per_page' => 1, 
  'orderby'=>'rand'
 ));
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
  <?php the_content(); ?>
<?php endwhile; ?> 

To find out more about Custom Post Types, I highly recommend Justin’s post and Devin’s Portfolio Theme. With both this tutorial and theme, you’ll be on your way to creating multiple Custom Post Types.

The difference between WordPress .COM & .ORG

I was recently asked by a colleague to explain the difference between .com and .org. With two WordPress websites to choose from, it can be a bit confusing sometimes.

WordPress.com is a hosted solution provided to you by the same folks who work on WordPress.org. This hosted solution is a great solution for anyone just wanting something simple, easy to use and ready in 5 minutes. Once signed up (for Free) you choose your theme and start blogging. With WordPress.com, everything is taken care of for you. Hosting, server and database set up, spam, backups, upgrades… Everything!
The drawbacks of this option is that you can only choose one of their available themes. Thus the selection is limited and customization is NOT possible. Neither is installing plugins.

WordPress.org is the self hosted solution. To set up a website using WordPress.org, you’ll need to visit the site, download all of the files and install them and the database on your hosting provider. Once you have everything installed, you can customize and install plugins to your hearts content. Anything is possible with WordPress.org, but it requires skills to set up and you’ll need to take care of backups, upgrade, spam, hosting… Everything!

Both options and Free and great, but will depend on your needs.

Matt Clark from tweetpages.com made this great video explaining the difference using the restaurant analogy. It’s worth a listen.

Setting up WordPress for development

If you’re like me, chances are, you won’t be building and launching a site in a day. Websites take time to set up, design, populate with content and test. As a web designers you will probably have clients who fall in one of these situations.

  • The client has a site, but requires a new one;
  • The client has nothing and needs a site.

Regardless of the situation, it’s best to develop the site in a folder that’s hidden from view. I usually like to develop my site in a wp folder. When people navigate to the site I’m working on they will see the current site or a Coming Soon page at www.domainname.com and the WordPress site in development will be at www.domainname.com/wp.

Another good thing to do while you are developing a site, is to set Privacy Settings to the second option “I would like to block search engines, but allow normal visitors“.

When you are ready to launch, giving WordPress its own directory takes only a few minutes.

  1. Navigate to Settings > General in your admin. Change the Site url from www.domainname.com/wp to www.domainname.com. DO NOT TOUCH WordPress url. Hit Save.
  2. In your FTP, navigate to your wp folder and download the .htaccess and index.php files. (Uploading them to your desktop is fine. You won’t need to keep these once you are done.)
  3. Open the index.php in your text editor and change the line that says:
    require('./wp-blog-header.php');
    to
    require('./wp/wp-blog-header.php');
  4. Save the file.
  5. Delete the old site from your root folder (making a back up might be a good idea) or the Coming Soon page.
  6. Upload this revised index.php and the .htaccess files to your root folder.

That’s it. You should now be able to see the site at www.domainname.com and access the WordPress admin at www.domainname.com/wp.

Don’t forget to change the privacy settings back to the first option, allowing Search engine to find your site.

These instructions are also found in the codex.

Adding pagination to your blog

Most WordPress themes come bundled up with “next page” and “previous page” links allowing you to navigate from older posts or newer posts. (The number of posts displayed on your blog overview and archives can be set in the Settings > Reading section of your admin.)

These links are great, but they can be improved by pagination which clearly indicates how many pages there are. As always there are many WordPress plugins for this, but there’s really no need. I personally prefer to keep plugins to a minimal and thus found the following tutorials very useful.


Kreisi’s tutorial
provides you with all of the code that you need to add pagination to your site. Once you’ve read his detailed information take a look at Veron’s post at Sparklette Studio. She made a few modifications and enhancements to the code.

Removing ellipses from WordPress excerpts

WordPress allows you to display either the full content or excerpts of your posts.

When creating a template for search results, I do find that displaying excerpts rather than a full post improves usability. However if you simply use the excerpt function, you’ll notice that ellipses […] are added at the end.

Personally I don’t find these useful at all and would prefer to have a link.

An easy way to fix this is by inserting the following code in your functions file:

function custom_excerpt_more($more) {
	return '<br /><a href="'. get_permalink() .'">read more...</a>';
}
add_filter('excerpt_more', 'custom_excerpt_more');

This will insert a break tag and add a link to the rest of the post.

You can also control the length of your excerpts if you wish. Simply add the following to your functions file.

function custom_excerpt_length($length) {
	return 20;
	}
add_filter('excerpt_length', 'custom_excerpt_length');

This function will limit your excerpts to the first 20 words.
Be careful though, if your post is less than 20 words, then the link won’t appear.