15

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?

3 Answers 3

17

Try this:

$query = new WP_Query('cat=4&meta_key=meta_long');

echo "var json=". json_encode($query->get_posts());
Sign up to request clarification or add additional context in comments.

Comments

5

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.

2 Comments

What's the purpose of decoding the json_encode()? Why not pass the encoded data directly to wp_localize_script()?
json_decode( json_encode() ) will convert all nested objects to arrays, without it you'll have a mix of stdObj and associative arrays
4

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 );

?>

1 Comment

$locations = array(); should be ouside the while loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.