How do you output JSON using wp_Query in wordpress?

Im trying to output or create json using wordpress message data combined with meta_key values.

This is the code that I use, but its incorrect JSON generation.

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

Any ideas on how to do this?

+6
source share
3 answers

Try the following:

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

Femi is suitable, but if your goal is to work with WP_Query data inside a JS file, I would suggest checking 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 a window.customQuery object in main.min.js

+3
source

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

 <?php // return in JSON format header( 'Content-type: application/json' ); // Needed if you want to manually browse to this location for testing define('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 loop while ( $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(); // output echo json_encode( $locations ); ?> 
+1
source

Source: https://habr.com/ru/post/892389/


All Articles