How do you output JSON using wp_Query in wordpress? How do you output JSON using wp_Query in wordpress? wordpress wordpress

How do you output JSON using wp_Query in wordpress?


Try this:

$query = new WP_Query('cat=4&meta_key=meta_long');echo "var json=". json_encode($query->get_posts());


Femi's approach is great, but if your goal is to work with WP_Query data inside of a JS file then I'd suggest checking out the wp_localize_script function.

/** * WP_Query as JSON */function kevinlearynet_scripts() {    // custom query    $posts = new WP_Query( array(        'category__in' => 4,        'meta_key' => 'meta_long',    ) );    // to json    $json = json_decode( json_encode( $posts ), true );    // enqueue our external JS    wp_enqueue_script( 'main-js', plugins_url( 'assets/main.min.js', __FILE__ ), array( 'jquery' ) );    // make json accesible within enqueued JS    wp_localize_script( 'main-js', 'customQuery', $json );}add_action( 'wp_enqueue_scripts', 'kevinlearynet_scripts' );

This will create the window.customQuery object in main.min.js.


Extending Femi's approach a little bit further, if you only want to return some of the loop data + custom fields try something like this:

<?php// return in JSON formatheader( 'Content-type: application/json' );// Needed if you want to manually browse to this location for testingdefine('WP_USE_THEMES', false);$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );require_once( $parse_uri[0] . 'wp-load.php' );// WP_Query arguments$args = array ('post_type'              => 'location','post_status'            => 'publish','name'                   => $_GET["location"],);// The Query$loop = new WP_Query( $args );//the loopwhile ( $loop->have_posts() ) : $loop->the_post();    // create an array if there is more than one result            $locations = array();     // Add in your custom fields or WP fields that you want     $locations[] = array(       'name' => get_the_title(),       'address' => get_field('street_address'),       'suburb' => get_field('suburb'),       'postcode' => get_field('postcode'),       'phone_number' => get_field('phone_number'),       'email' => get_field('email_address')     );endwhile;wp_reset_query();// outputecho json_encode( $locations );?>