Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I feel like this is going to be one of those slap yourself on the head questions, but here it goes anyway:

I have a multi-dimensional array of data:

Array
(
    [0] => Array
        (
            [id] => 1033
            [zip] => 27604
            [distance] => 0
        )

    [1] => Array
        (
            [id] => 1024
            [zip] => 27615
            [distance] => 6
        )

)

The id field in each is the post ID and what I'm really after. What I've tried thusfar is something like:

foreach( $locations as $post ) {
    setup_postdata($post['id']);

    echo get_the_title();

}
wp_reset_postdata();

with no luck. Am I approaching this all wrong - what's the best way to get that darned ID value to run through setup_postdata()?

I still need to reference the other data in the multi-dimensional array (zip and distance).

share|improve this question

1 Answer 1

up vote 2 down vote accepted

There was a similar (related) question on here recently. The upshot is that get_the_title() uses the global $post when no argument is passed. And setup_postdata() doesn't set that global (a mistake I've made before now ).

In your case, I would do the following:

foreach( $locations as $post ) {
    setup_postdata(get_post($post['id']));

    echo get_the_title($post['id']);

}
wp_reset_postdata();

Note: setup_postdata() takes a post object, not ID, so if you're going to use it, use it with get_post().

share|improve this answer
    
Appreciate the response - is there even an advantage to using setup_postdata() then based on how the results are formatted (since I have to pass in the $post['id'] var in this case)? –  Zach Nov 19 '12 at 21:12
    
It's not needed for just the title - but investigating the source, setup_postdata() sets up the global $pages, which get_the_content() uses. So if you want to output content, then yes. I would use it anyway, to avoid any confusing bugs later down the road. –  Stephen Harris Nov 19 '12 at 21:18
    
Thanks for digging into that further - appreciate it! –  Zach Nov 19 '12 at 21:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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