Quick WordPress custom loop

Update: There is a new improved version of a custom WordPress loop here

This is a short example of how to quickly produce a custom loop in WordPress.

I usually use the thesis theme frame work so this code would usually live in the custom_functions.php file. For other themes this can go in the functions.inc.php file.

Firstly here is the function to format the output of the posts.

This function also supports the thesis post images. So if you’re using this theme and use post images they will be displayed, if you’re not you can delete lines 18-24 (the if statement)

function cnCustomLoops( $args ){
		global $post;
		$output = ""; // empty the string
		// The Query
		$the_query = new WP_Query( $args );

		// The Loop
		while ( $the_query->have_posts() ) : $the_query->the_post();

			$permalink = get_permalink();
			$title = get_the_title();
			$theexcerpt = get_the_excerpt();

			$output .= "<div class='format_text entry-content'>";
			$output .= "<h3>";
			$output .= "<a href='" . $permalink . "'>" . $title . "</a>";
			$output .= "</h3>";
			if (get_post_meta($post->ID, 'thesis_post_image', true) != ""){

				$image = get_post_meta($post->ID, 'thesis_post_image', true);
				$url = "http://url-to-your-blog/wp-content/themes/thesis_181/lib/scripts/thumb.php?src=" . $image .  "&w=150&zc=1&q=100";

				$output .= "<img src='" . $url . "' alt='" . $title . "'";
			}
			$output .= "<p>";
			$output .= $theexcerpt;
			$output .= "</p>";
			$output .= "<a class=\"read-more-button\" href='" . $permalink . "'>Read More</a>";
			$output .= "</div>";
		endwhile;
		wp_reset_postdata();

		return $output;
}

Then you need to code to fire the loop

function sampleLoop(){
$args = array(
	'posts_per_page' => 2,
	'cat' => 11,
	'post_type' => 'post',
	'orderby' => 'rand'
);
echo cnCustomLoops( $args );

}

You can use this code to support custom post types, see the line ‘post_type’, change this to the name of your custom post type.

For full details on the parameters to place in the $args, check out this page on the WordPress Codex

You can use this code in lots of places, I commonly use it in a footer area so that you can display posts and post images of the more recent posts from a particular category. You can also use thesis hooks to display a loop in another part of the page.

Enjoy!