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'm having an issue thinking today and ran into a brick wall.

What I'm trying to do it take 3 different custom field data for posts and combine them into an array that I can then json encode for use in some jquery.

The three fields I want to use are the 'project title' and a custom field of 'latitude' and 'longitude'. And this is what I'm looking to get:

Array ([0] => array ([0] => "project title", [1] => "latitude", [2] => "longitude"),[1] => array ([0] => "post title", [1] => "latitude", [2] => "longitude")

I'm thinking i need a foreach loop, but just can't get it to work in my head. Any help would be greatly appreciated!

share|improve this question

1 Answer 1

up vote 0 down vote accepted

If I'm understanding your issue correctly, and if by 'project title' you mean the content of the post_title field, then it'll look something like this:

$post_data = array();

$my_query = new WP_Query( $whatever_your_args_are );
if ( $my_query->have_posts() ) {
    while ( $my_query->have_posts() ) {
        $my_query->the_post();
        $post_data[] = array(
            'project_title' => get_the_title(),
            'latitude'      => get_post_meta( get_the_ID(), 'latitude', true ),
            'longitude'     => get_post_meta( get_the_ID(), 'longitude', true )
        );
    }
}

echo json_encode( $post_data );

I changed your example just a touch so that the JSON object would have the values keyed nicely (project_title, latitude, longitude) instead of the more opaque numerical keys. I'm also assuming that you're using WP_Query to query and loop through the posts. If not, you can replace the WP_Query stuff with a loop over whatever content you've pulled from the DB.

share|improve this answer
    
Boom! You're the brain kick I needed this morning! Thanks, Boone! –  coloradohiker Mar 22 '12 at 15:37
    
Cha-cha-cha-ching! –  Boone Gorges Mar 22 '12 at 15:47

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.