menu
書いてる野郎
orebike@gmail.com
HTML に吐き出している内容を JSON で吐きたいという場合がある。そのやり方。
別に何も特別なことは無い。テーマのテンプレファイルに PHP コードをゴリゴリ書くだけである。
header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=utf-8"); $result = new WP_Query($params); $output = array(); if($result->have_posts()): while($result->have_posts()): $result->the_post(); $item = array( "url" => get_the_permalink(), "date" => get_the_date('Y-m-d'), "title" => get_the_title() ); $output[] = $item; endwhile; endif; echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); die();
雑だがこんな感じになる。 wp_send_json
を使うというやり方もあるっぽいが、エンコードのオプションが自分の環境では効かなかった。