json取得
Wordpressの4.7から標準対応になったWP_REST_APIが大変便利だったのでここに使い方を纏めておきます。
まずは対応しているサイトがどうかを下記のURLを入れて確認してみましょう。
そのサイトの全投稿記事のjsonデータが見れたらWP_REST_APIに対応しております。
http://example.com/wp-json/wp/v2/posts
特定の記事だけを指定したい場合は下記のURLです。
http://example.com/wp-json/wp/v2/[投稿ID]
最新記事10件だけ表示させたい場合は
http://example.com/wp-json/wp/v2/posts/?filter[post_per_page]=10
json出力例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>WP REST APIテストページ</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON( "http://test55.sakura.ne.jp/wp-json/wp/v2/posts/?filter[post_per_page]=10", function(results) {
$.each(results, function(i, item) {
var date = new Date(item.date);
yy = date.getFullYear(date);
//console.log(yy);
mm = date.getMonth() + 1;
//console.log(mm);
dd = date.getDate();
//console.log(dd);
$("ul#mylist").append('<li class="flex"><time datetime="' + yy + mm + dd + '">' + yy + '/' + mm + '/' + dd + '</time><a href="' + item.link + '">' + item.title.rendered + '</a></li>');
});
});
});
</script>
</head>
<body>
<h2>お知らせ 最新10件</h2>
<ul id="mylist">
</ul>
</body>
</html>