loading

WordPress Helper Functions, Part 1

07.02.2010 | Tagged as WordPress

Kitty Cat High FiveWordPress is awesome. Me likey a lot. However, most things I like also tend to be tragically flawed. This is not the case with WordPress. Instead, its shortcomings are not OOTB issues. They are a result of the system's amazing flexibility. Luckily, the WordPress API, coupled with improving documentation and some elbow grease, smoothes these techno-wrinkles right out.

Posts and Categories

Arguably, the most common helper function I use is the following:

/**
 * Pull the most recent posts of a category
 */
function get_posts_by_category($category_id, $posts_per_page) {
 $posts = null;
 
 $args = array(
  'cat' => $category_id,
  'post_type' => 'post',
  'post_status' => 'publish',
  'posts_per_page' => $posts_per_page,
  'orderby' => 'date',
  'order' => 'DESC'
 );
 
 $query = new WP_Query($args);

 $posts = $query->posts;
 
 wp_reset_query();  // Restore global post data stomped by the_post().
 
 return $posts;
}

The function above is quick and dirty way to get lists of category posts wherever you may need them in your theme or plugins. Pre-WordPress 3.0, I would typically use categories as content types — transforming a post into a rudimentary business object.  So, having the ability to pull specific types of posts for a variety of uses became increasingly important.  

Below is a simple example of how to leverage this function:

/**
 * Display a category posts as a list
 */
function display_category_as_list($category_id, $posts_per_page = 3) {
 $posts = get_posts_by_category($category_id, $posts_per_page);

 echo '<ul">';
 
 foreach ($posts as $post) {
  echo '<li>'. 
   '<span class="title">' . date("F j, Y", strtotime($post->post_date)) . 
   '<strong><a href="' . get_permalink($post->ID) . '">' . $post->post_title . 
   '</a></strong></span></li>';
 }
 
 echo '</ul>';
}

Obviously, the above could be purdied up a bit and modified to do pretty much whatever you'd like.

Render Post Content Outside the Loop

Another stubborn modification I generally make is the need to render a post's body outside of the normal flow of things. I especially like to do this when an interface can be livened up with some jQuery-style animations. Getting the post's content is easy, just call "$post->post_content". However, the returned string will be devoid of some crucial UI elements like breaks and paragraph tags.  Luckily, there is a perfect parser function for rendering the body, see below:

/**
 * Apply content filters to data pulled outside of publishing loop
 */
function filter_content_outside_loop($content) {
 $content = apply_filters('the_content', $content);
 $content = str_replace(']]>', ']]>', $content);
 
 return $content;
}

Well, that's all I have at the moment and would love to see some other helpful functions from any of you PHP aficionados.

< Previous Post Next Post >