I’m trying to get all posts from a particular custom post type using the following code:
$auctions = get_posts(array('post_type' => 'auction'));
print_r($auctions);
echo '<select>';
foreach ($auctions as $auction) {
echo '<option value="' . $auction->ID . '">' . $auction->post_title . '</option>';
}
echo '</select>';
Although the print_r() call shows data, the foreach seems to ignore it and doesn’t print anything. Any ideas?
Any help would be appreciated
print_r() output:
Array (
[0] => WP_Post Object (
[ID] => 36
[post_author] => 1
[post_date] => 2013-05-19 10:58:45
[post_date_gmt] => 2013-05-19 08:58:45
[post_content] =>
[post_title] => My Title
[post_excerpt] =>
[post_status] => publish
[comment_status] => closed
[ping_status] => closed
[post_password] =>
[post_name] => my-title
[to_ping] =>
[pinged] =>
[post_modified] => 2013-05-24 09:55:53
[post_modified_gmt] => 2013-05-24 07:55:53
[post_content_filtered] =>
[post_parent] => 0
[guid] => http://domain.com/?post_type=auction&p=36
[menu_order] => 0
[post_type] => auction
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
)
You can use
wp_query()
for this to workDocumentation for
WP_Query
https://codex.wordpress.org/Class_Reference/WP_QueryPerhaps because
get_posts
returns an object, you need to setup post data per Codex get_posts. Replacing line 4:Try it without get_posts(). I currently have a similar function that works like this:
Edit: Actually I’m not sure why this isn’t working since codex clearly says to use
echo $post->ID;
with get_posts. http://codex.wordpress.org/Function_Reference/get_posts#Access_all_post_dataDoes this make any difference for you?
@gregory was actually right, but had a few typos… There was a closing
;
missing from the array and at the endreset_postdata();
has to becomewp_reset_postdata();
.This should work just fine now… It works great for me, without any problem!
Hope this will help!