It's Friday, it's late, I've probably done this before in the work I've done before, but I'm drawing a blank. What is the best way to stay within the Wordpress framework and collect a list of your custom post types?

This is being used in the admin side and the code exists inside a plugin. I've got a custom post type, though this should be the same question for regular posts.

Essentially, I want a pulldown which has all of the posts (under a custom post type) sorted by a person's name. The tough part, the name is stored as a custom post meta (custom field). I could simplify things and make the post title (currently ignored and unused) be the person's name.

There is no relevant code to supply, this is just a general question aimed at fellow plugin developers.

Is there a function that collects posts in to an array or object?

  • Both get_posts and WP_Query allow fetching based on meta and post type, and additionally both return an array of objects. So essentially your answer would be to call one of those with the applicable args. Unless you feel there's something they don't provide that you need(but is missing from your question). – t31os Dec 24 '11 at 12:56

You're looking for get_post_types();

It returns an array of every post type registered. To get the labels though, you'll need to do something like:

foreach (get_post_types() as $pt) :
    $obj = get_post_type_object($pt);
    echo $obj->labels->name;
  • Thanks, but not what I'm asking about. I'm looking for a function that will return individual posts as a row in an array, not the post types. – Exit Dec 24 '11 at 0:37
  • My brain is jello. It's simply: $array = get_posts(array('post_type' => 'custom_post_type_here')); – Exit Dec 24 '11 at 0:45
  • Sorry, got too focused on the "collect a list of your custom post types" line. This gets you all the post types, in that foreach loop do a new WP_Query: codex.wordpress.org/Class_Reference/WP_Query Or you can set the post_type argument to ANY – CookiesForDevo Dec 24 '11 at 0:47
  • I didn't like how wasteful using get_posts was, so I did just that, used a WP query. I thought there might be a function out there to wrap this, but I used the following: $names = $wpdb->get_results("SELECT ID,post_title FROM {$wpdb->prefix}posts WHERE post_status='publish' and post_type='country-zones' ORDER BY post_title;",ARRAY_N); – Exit Dec 24 '11 at 1:15
  • get_posts() is a very thin wrapper around WP_Query, so it's really not wasteful, just FYI. What is more wasteful IMO is both of them effectively doing a SELECT * when all you really want are post_id and a few other fields. FWIW. – MikeSchinkel Dec 24 '11 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.