如何在wordpress中使用wp_Query输出JSON?

jru*_*ter 9 php arrays wordpress json

我试图输出或创建json使用wordpress发布数据加上meta_key值.

这是我正在使用的代码,但它不正确地形成了JSON.

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

echo "var json=". json_encode($query);
Run Code Online (Sandbox Code Playgroud)

有关如何做到这一点的任何想法?

Fem*_*emi 16

试试这个:

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

echo "var json=". json_encode($query->get_posts());
Run Code Online (Sandbox Code Playgroud)


Kev*_*ary 5

Femi 的方法很棒,但是如果您的目标是在 JS 文件中处理 WP_Query 数据,那么我建议您查看该wp_localize_script函数。

/**
 * 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' );
Run Code Online (Sandbox Code Playgroud)

这将window.customQuerymain.min.js.

  • `json_decode( json_encode() )` 会将所有嵌套对象转换为数组,没有它,你将混合使用 `stdObj` 和关联数组 (2认同)