【问题标题】:JSON file generated with wp_send_json returns 404使用 wp_send_json 生成的 JSON 文件返回 404
【发布时间】:2016-11-16 19:48:40
【问题描述】:

我正在创建一个 JSON API 来修改重写规则,以便可以从 movies.json 访问它。 如果我导航到http://myurl.com/movies.json,我可以看到包含预期内容的 json 文件,但如果我使用 AJAX 进行调用,它将返回“404 Not Found”。

这是我重写 url 的代码:

public function rewrite_url() {
    global $wp_rewrite;
    add_rewrite_tag( '%movies%', '([^&]+)' );
    add_rewrite_rule( 'movies.json', 'index.php?movies=all', 'top' );
}

这是我输出 json 文件的代码:

public function json_output() {
   global $wp_query;

    $movies_tag = $wp_query->get( 'movies' );


    if ( ! $movies_tag ) {
        return;
    }

    $movies_array = array();

    $args = array(
        'post_type' => 'movies',
        'posts_per_page' => 100,
    );


    $movies_query = new WP_Query($args);
    if ( $movies_query->have_posts() ) : while ( $movies_query->have_posts() ) : $movies_query->the_post();
        $post_id = get_the_ID();

        $movies_array['data'][] = array(
           'id' => $post_id,
           'title' => get_the_title(),
           'poster_url'=> get_post_meta($post_id, 'poster_url', true),
           'rating' => get_post_meta($post_id, 'rating', true),
           'year' => get_post_meta($post_id, 'year', true),
           'short_description' => get_post_meta($post_id, 'short_description', true)
        );

    endwhile;

    wp_reset_postdata(); 

    endif;
    header("Access-Control-Allow-Origin: *");
    header( 'Content-Type: application/json;' );
    wp_send_json( $movies_array );

}

知道为什么会这样吗?谢谢

【问题讨论】:

    标签: php json wordpress


    【解决方案1】:

    刚刚遇到同样的问题;添加header("HTTP/1.1 200 OK"); 似乎可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 2014-03-31
      • 2021-08-02
      • 2020-05-18
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      相关资源
      最近更新 更多