How to get an array of custom post type item objects in WordPress

July 29th, 2013 by Sean Barton Leave a reply »

A quick one today. I keep having the need to write the same function over and over again. This is a simple function to get an array of post type item objects. The query itself is based on WP_Query (query_posts) however for those of you that don’t know a great deal about it’s execution this might come in useful.

I imagine the sort of person who is going to use it is likely to be someone who knows how to make a custom post type either using a plugin or modifying the code from the Codex and then subsequently wants to know what to do with it. This code is roughly the basis of many a WP plugin including a few of my own… SB Mini Features for example creates the post type and then adds this code to a shortcode call outputting some basic HTML and then styling it. Have a think.. the possibilities are endless!

function get_post_type_items($post_type, $args_extended=array()) {
		global $post;
		$old_post = $post;
		$return = false;

		$args = array(
			, 'post_status'=>'publish'
			, 'showposts'=>-1
			, 'order'=>'ASC'
			, 'orderby'=>'title'

		if ($args && count($args_extended)) {
			$args = array_merge($args, $args_extended);


		if (have_posts()) {
			global $post;
			$return = array();

			while (have_posts()) {
				$return[get_the_ID()] = $post;

		$post = $old_post;

		return $return;		

1 comment

Leave a Reply