code snippets

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.

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&child_of=2&depth=1&title_li=');
} elseif (is_page(3) || $post->post_parent==3) {
wp_list_pages('sort_column=menu_order&child_of=3&depth=1&title_li=');
} elseif (is_page(4) || $post->post_parent==4) {
wp_list_pages('sort_column=menu_order&child_of=4&depth=1&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?

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;
}
 function highlight_columns_display($highlight_columns){
 switch ($highlight_columns)
 {
   case "description":
   the_excerpt();
   break;               
 }
}

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.

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.

Use jQuery to hide/reveal children of a WordPress page

I recently launched a beautiful website for Kurt Jurek, registered acupuncturist and herbalist. As some of you may know, Chinese medicine can be used to treat a huge amount of ailments. As a result when putting together content, the amount can be overwhelming and difficult to organize. Combine this with the need to use a CMS and you’re task is quite daunting. This is when adding a bit of JQuery to your WordPress theme helps.

My number one task when setting up WordPress as a CMS for a client is to make updates easy to understand. If clients need to use HTML in their admin, then I consider this a failure. WordPress in itself is quite easy for most people to grasp and understand and it should be the case at all times.
Continue reading »

Modifying the WordPress admin

I’ve been using WordPress to build 99.5% of my sites lately. Even if a particular client doesn’t need a blog or won’t be making frequent changes, I do like to provide the ability to update content if needs be.

As a result, the WordPress back end has too many features for such a client. After reading the tutorial from Six Revisions, I’ve been modifying the WordPress admin, but using the following:

/* Remove Posts and Tools from Admin menu items */
function remove_menu_items() {
global $menu;
$restricted = array(__('Posts'),__('Tools'),__('Comments'),__('Links'));
end ($menu);
while (prev($menu)){
$value = explode(' ',$menu[key($menu)][0]);
if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){
unset($menu[key($menu)]);}
}
}

add_action('admin_menu', 'remove_menu_items');

Once added to my functions.php file, the menu items posts, tools, comments and links disappear. How handy is that?

Updates to the WordPress Comment Form

Justin Tadlock recently wrote a great post and tutorial aimed at theme developers. His article pointed out that with the release of WordPress 3.0, a new function for handing comment forms: comment_form(), was introduced.

This new function offers much more flexibility for plugin authors and is really easy to use. All you have to do is open up your comments.php file and locate this bit of code:

<div id="respond">

Lots of HTML code to output form elements.

</div>

and replace it with:

<?php comment_form(); ?>

You may also need to tweak your CSS, but overall, that’s the only change needed.

I took Justin’s advice and updated my basic theme and noticed a few things.

  • The default title is Leave a Reply
  • The default submit value is Post a Comment
  • The comment after the form ‘You may use these HTML tags…‘ was added

In order to change these easily, I updated my function file with the following code:

<?php
//Change comment form defaults

add_filter( 'comment_form_defaults', 'basic_comment_form_defaults' );
        function basic_comment_form_defaults( $defaults ) {
                $defaults['label_submit'] = __( 'Submit' );
                $defaults['title_reply'] = __( 'Leave a Reply' );
                unset($defaults['comment_notes_after']);
                return $defaults;
        }
?>

Displaying latest and most popular blog posts in your WordPress footer

Fat footers are very handy for displaying additional information on your site. On a previous version of this website I used to display the latest blog posts, while on this newer version I opted to display the popular posts. I thought I would share these code snippets here.

Display Recent Blog Post

In your footer.php file, simply use the following code:

<ul>
<? query_posts('showposts=10');?>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

Simply change ‘showposts=10′ to whatever number you want to display more or less than 10 posts.

Display Most Popular Blog Posts

“Most popular” posts in this case is defined by the posts that have the most comments. In order to select these, the following pieces need to be used:

1. Add the following function to your function file:

function most_popular_posts($no_posts = 10, $before = '<li>', $after = '</li>', $show_pass_post = false, $duration='') {
global $wpdb;
$request = "SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS 'comment_count' FROM $wpdb->posts, $wpdb->comments";
$request .= " WHERE comment_approved = '1' AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = 'publish'";
if(!$show_pass_post) $request .= " AND post_password =''";
if($duration !="") { $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
}
$request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
$posts = $wpdb->get_results($request);
$output = '';
if ($posts) {
foreach ($posts as $post) {
$post_title = stripslashes($post->post_title);
$comment_count = $post->comment_count;
$permalink = get_permalink($post->ID);
$output .= $before . '&raquo; <a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a>' . $after;
}
} else {
$output .= $before . "None found" . $after;
}
echo $output;

In this function, I’ve set the number of posts to 10 – ‘$no_posts = 10‘. Just change this number to display more or less posts.

2. Insert the following in your footer.php

<ul>
<?php most_popular_posts(); ?>
</ul>

WordPress revision control

In an earlier post, I discussed the handy revision control plugin. Plugins are awesome and I truly have immense respect for plugin developers, but I do find them a bit tedious to maintain and sometimes a bit of an overkill.

I am constantly fiddling and updating over 30+ client sites at a time. If WordPress and plugin updates didn’t come out as frequently, I would be more than happy to load my sites with dozens of plugins, but I do find simpler non-plugin methods more handy.

I recently discovered that post revisions can be disabled or limited simply by adding the following bit of code to the wp_config.php file.

define('WP_POST_REVISIONS','5'); //Will limit revision to 5 revisions

define('WP_POST_REVISIONS','false'); //Disables revisions totally

Personally, I think that one line of code is better than a plugin.

Page 1 of 212