php - Controlling the output of a json feed -
i'm trying pull out json feed wordpress query. need json formatted [{"id":"1","title":"title"},{"id":"2","title":"title2"}]
the json_encode function not pulling out specific format: items not separated commas , i'm missing initial , final [ ]
i made code echoing missing elements, works good, final comma, because of echo making script reading fail.
<?php $args = array( 'post_type' => 'location', 'posts_per_page' => -1 ); $locations = new wp_query($args); if($locations -> have_posts()): echo '['; while ($locations->have_posts()) : $locations->the_post(); $coords = get_field('coordinates'); $pid = get_the_id(); $json["id"] = $pid; $json["name"] = get_the_title(); $json["lat"] = $coords['lat']; $json["lng"] = $coords['lng']; $json["address"] = get_field('address'); $json["address2"] = get_field('address_2'); $json["city"] = get_field('city'); $json["state"] = get_field('state'); $json["postal"] = get_field('zip_code'); $json["phone"] = get_field('office_phone'); $json["fax"] = get_field('office_fax'); $json["web"] = apply_filters('the_permalink', get_permalink()); echo json_encode($json); echo ','; endwhile; echo ']'; endif; ?>
i know echoing elements not correct way it, , i'm doing wrong on encode, that's why it's pulling out without right formatting.
i have been researching days , couldn't find way create json_encode echoing , @ same time controlling fields show wordpress query.
i appreciate in advance solution/lead solve this.
you're adding wrong in loop. want create array, , present array json.
if($locations -> have_posts()): $data = array(); while ($locations->have_posts()) : $locations->the_post(); // add location stuff $data array $data[] = array( 'id' => $pid, 'name' => get_the_title(), // etc.... ); endwhile; // present json echo json_encode($data); endif;
Comments
Post a Comment