Formatting Query into Json for AJAX call
-
Hey all, looking to have a nested loop feed data into a json-able php array, encode that array, then be able to call it via AJAX. I have the AJAX part down, but making the array properly is giving me some trouble.
Code for what the JSON should look like (rough outline):
[{ "topic-title" : [ { "title" : "the_title", "link" : "get_permalink" },{ "title" : "the_title", "link" : "get_permalink" } // etc. ] , "next-topic-title : [ { "title" : "the_title", "link" : get_permalink" }, { "title" : "the_title", "link" : "get_permalink" } // etc. ] // etc. }]
It should be echoed from this code, but I’m getting ‘undefined’ when I console.log it in the browser.
function reload_topics() { $final = array(); $tax_sh = get_terms( array( 'section' ),array( 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true, 'hierarchical' => true ) ); foreach ($tax_sh as $term) { $argsh = array( 'post-type' => 'custom-post-type', 'tax_query' => array( array( 'taxonomy' => 'section', 'field' => 'slug', 'terms' => $term->slug ) ) ); $content = array(); $this_term = $term->slug; $content[$this_term] = array(); $inner_query = new WP_Query($argsh); if( $inner_query -> have_posts() ) : while( $inner_query -> have_posts() ) : $inner_query->the_post(); $this_post = array("title" => get_the_title(), "link" => get_permalink($post->ID)); array_push($content[$the_term],$this_post); endwhile; else: endif; array_push($final,$content); } $final_encode = json_encode($final); echo $final_encode; die(); }
If there is a much easier way to do this or a tutorial I can work through that would be much appreciated, but I haven’t been able to enter the correct terms into Google to find a good tutorial, except the upvote downvote tutorial that is on a few sites; it does not cover this exactly, but definitely helped with the AJAX part.
Thanks!
- The topic ‘Formatting Query into Json for AJAX call’ is closed to new replies.