简体   繁体   English

您如何在 wordpress 中使用 wp_Query output JSON?

[英]How do you output JSON using wp_Query in wordpress?

Im trying to output or create json using wordpress posts data coupled with meta_key values.我试图 output 或使用 wordpress 发布数据和 meta_key 值创建 json。

This is the code I'm using, but its forming the JSON incorrectly.这是我正在使用的代码,但它错误地形成了 JSON。

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

echo "var json=". json_encode($query);

Any ideas of how to do this?关于如何做到这一点的任何想法?

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. Femi 的方法很棒,但如果您的目标是使用 JS 文件中的 WP_Query 数据,那么我建议您查看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 .这将在 main.min.js 中创建window.customQuery 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:进一步扩展 Femi 的方法,如果您只想返回一些循环数据 + 自定义字段,请尝试以下操作:

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

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM