Im trying to output or create json using wordpress posts data coupled with meta_key values.
This is the code I'm using, but its forming the JSON incorrectly.
$query = new WP_Query('cat=4&meta_key=meta_long');
echo "var json=". json_encode($query);
Any ideas of how to do this?
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 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 );
?>
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With