• Feed RSS

10 Code Snippets WP Theme Developers Should Have on Speed Dial

"
One of the ways we endeavor to improve productivity when building WordPress templates is to have snippets of code available to us very quickly, through the use of tab-triggered shortcuts. In this article I will share with you 10 of my most-used snippets that I feel every developer should have at their fingertips.


Coda tab-triggered shortcuts Looking to take your coding speed to the next level?
As someone who builds a lot of WordPress themes from scratch 5 or more days per week, anything I can do to make my job less laborious or monotonous is a good thing! Repetitive tasks soon become overwhelming, and they can easily become the cause of a loss enthusiasm in a project, or indeed even an entire job.
Tab-triggered shortcuts are simply a series of user-defined keystrokes followed by a press of the TAB key. When you press the tab key, the text you typed prior to pressing the tab key is replaced with any text/code that you specify when you configure the shortcut. Tab-triggered shortcuts came to my attention through using Coda. However, this shortcut functionality is not exclusive to Coda.
A lot of text editing applications enable you to specify a sequence of key-presses to trigger a shortcut. Some examples include TextMate, E-TextEditor and Sublime Text. In fact, a lot of these applications allow you to download and add packages of code snippets that have been created for a similar purpose by other developers – saving you even more time! You could also achieve a similar effect by using something like TextExpander (Mac) or ActiveWords (PC) which is a background application that allows you to turn a few keystrokes in to anything you require – in any application.
So, without further hesitation, let me introduce you to 10 code snippets that I believe all WordPress theme developers should have on speed dial:
Note: You can obviously use any “shortcut” text that you prefer. I’ll share my own, but feel free to use other text to suit your own workflow.

1. Template Directory

Shortcut: tp[tab]
This snippet of code is used to return an absolute URL to the current theme directory. It is useful for embedding images and calling scripts, and should be use in place of typing a relative URL.

Code

<?php bloginfo('template_directory'); ?>

Example

<img src="<?php bloginfo('template_directory'); ?>/images/header.jpg" alt="Header" />
 <script src="<?php bloginfo('template_directory'); ?>/js/jquery.js" type="text/javascript">

2. Custom Query

Shortcut: query[tab]
This snippet of code places a custom WordPress query on your page. This is great for templates that have multiple queries running on them. You might use this for querying featured posts to render an image slideshow, or to simply display a list of news posts on a page or in the sidebar, as an alternative to widget functionality (as it’s more flexible).

Code

<?php $query = new WP_Query(''); ?>
 <?php if($query->have_posts()) : ?><?php while($query->have_posts()) : $query->the_post(); ?>
 <?php the_content(); ?>
 <?php endwhile; endif; ?>

Example

<?php $featured = new WP_Query('showposts=3&tag=featured'); ?>
 <?php if($featured->have_posts()) : ?>
 <ul id="featured">
 <?php while($featured->have_posts()) : $featured->the_post(); ?>
 <li><a href="" title="<?php the_title(); ?>"><?php the_post_thumbnail(‘full’); ?></a></li>
 <?php endwhile; ?>
 </ul>
 <?php endif; ?>

3. If Have Posts, While Have Posts, The Post

Shortcut: hp[tab]
This snippet of code is used all over WordPress template files. It is the beginning of The Loop (http://codex.wordpress.org/The_Loop), and is needed to fetch content from your WordPress database.

Code

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

Example

<div class="content">
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
 <h1><?php the_title(); ?></h1>
 <?php the_content(); ?>
 <?php endwhile; else: ?>
 <p>Sorry, no posts found.

 <?php endif; ?>
 </div>

4. The Permalink

Shortcut: link[tab]
This snippet is used inside the loop to return an absolute URL to the item(s) your loop is processing – usually posts or pages. The link that is output on the page will vary depending on your permalink structure – but should your permalink structure change, you will not need to change this code.

Code

<?php the_permalink(); ?>

Example

<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

5. Custom Field Value

Shortcut: cf[tab]
Custom fields add a huge amount of flexibility to a template. The limit really is either your imagination, or a self-defined line where you believe functionality is too in-depth for custom fields, and should instead be implemented through a plugin or custom post type.

Code

<?php echo get_post_meta($post->ID, 'custom-field-key', true); ?>
One of my more recent uses for custom fields was on a client’s website that had a library of information about guitar effects pedals. The owner of said website affiliated with a few different online stores – and gets a commission if one of these effects pedals sells should a customer buy one after following a link from their website. The referral links worked so that my client could link directly to the product on one of the affiliate websites, and simply put some referrer information at the end of the URL.
I had set up a custom post type for the effects pedals, so using a custom field seemed like a simple step forward to achieve an easy way for the client to manage this data. The custom field key was “affiliate” and they added the link in the value box. On the template, the custom field was used to output a “Buy Now!” button.

Example

<a class="button_buynow" href="<?php echo get_post_meta($post->ID, 'affiliate', true); ?>" title="Buy <?php the_title(); ?>">Buy Now!</a>

6. Custom Menu

Shortcut: menu[tab]
WordPress 3.0 introduced a fantastic new menu system, which moved us all away from using “wp_list_pages” and a bulky “exclude pages from lists” plugin. It’s a simple function call, but I use it at least once per website, so I turned it into a tab-triggered shortcut.

Code

<?php wp_nav_menu( array( 'menu' => 'Navigation', 'sort_column' => 'menu_order' ) ); ?>
If you are building a theme to offer as a download, then you will likely use the theme_location parameter so that users can specify their own menu/multiple menus. My templates are usually built for clients, and by default I tend to name the menu “Navigation”, so in five key-strokes I have done all that is necessary to get the navigation onto the page. The rest is handled with CSS.

7. WordPress Include

Shortcut: wpinc[tab]
The syntax to include a file in WordPress is a bit different to the standard PHP include. I use WordPress includes in themes a lot when I’m working with custom post types and taxonomies. I like to have each post type and taxonomy in a separate file, for no reason other than to keep things clean and easy to read. However, doing it this way means the files have to be included in the theme’s functions.php file.

Code

<?php include (TEMPLATEPATH . '/filename.php'); ?>

Example

<?php include (TEMPLATEPATH . '/taxonomy_manufacturers.php'); ?>

8. Dynamic Sidebar

Shortcut: side[tab]
I can never exactly remember the code to display a dynamic sidebar, and even though I don’t use it that often, it’s a bit long to type out manually when I do.

Code

<?php if(!function_exists('dynamic_sidebar') || !dynamic_sidebar('Sidebar') ) : ?><?php endif; ?>
This of course relies on the other part of the code, which enables dynamic sidebars in the theme, being in the functions.php file
<?php
if (function_exists('register_sidebar') )
 register_sidebar(array(
     'before_widget' => '<div class="widget">',
     'after_widget' => '</div>',
     'before_title' => '<h2>',
     'after_title' => '</h2>',
 ))
;
?>

9. Header & Footer Code

Shortcut: start[tab]
When ever I begin building a WordPress template, I put everything in the index.php file. I move everything to the separate header.php, footer.php and sidebar.php files once I’ve got the index.php how I want it – that’s just the way I like to work. All of my projects begin with the same code.

Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">

 <head profile="http://gmpg.org/xfn/11">
 <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />

 <title><?php wp_title(''); ?></title>

 <meta name="generator" content="WordPress <?php bloginfo('version'); ?>" /> <!-- leave this for stats -->

 <link rel="stylesheet" href="" type="text/css" media="screen" />
 <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="<?php bloginfo('rss2_url'); ?>" />
 <link rel="alternate" type="text/xml" title="RSS .92" href="<?php bloginfo('rss_url'); ?>" />
 <link rel="alternate" type="application/atom+xml" title="Atom 0.3" href="<?php bloginfo('atom_url'); ?>" />
 <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />

 <?php wp_enqueue_script('jquery'); ?>
 <?php wp_head(); ?>

 </head>

 <body <?php body_class(); ?>>

 <?php wp_footer(); ?>
 </body>
 </html>

10. Get Header/Footer/Sidebar

Shortcut: gh[tab], gs[tab], gf[tab]
This is a three-in-one, but these code snippets are used in every WordPress template multiple times. Imagine how many seconds you could save not typing them out every time you used them! Yes, yes, you can copy and paste too – I know! See if you can guess which shortcut outputs which code…

Code

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

Conclusion: Share Your Snippets!

As many of you are no doubt aware, the WordPress codex is very big. I think the key thing to try to maintain here is that only the most useful, longest and/or most used code snippets should be turned into tab-triggered shortcuts. Otherwise we simply go from trying to remember portions of code to trying to remember key-stroke sequences we have set up, which can be even more frustrating… plus, if you get caught on a computer other than your main workhorse, it can be tricky to remember the original code. The rule of thumb is that these should be time-savers, not crutches ;)
I hope you share any snippets that you do/would use in this manner in the comments!
"