Moral Hazard!!

ドラマーが音楽やホームページやガラクタを作るよ。

WordPress REST APIから記事を取得して表示する(PHP)

No Comment html,css,php,wordpress,,

PHPで一度REST APIをサイト内に取り込み、静的ページのjsで取得することでクロスドメイン制限を回避。

log.php

$data = json_decode(file_get_contents('https://example.com/wp-json/wp/v2/posts?_embed'));

foreach ($data as $value) {
    $title = $value->title->rendered;
    $link =  $value->link;
    $year = substr($value->date, 0, 4);
    $month = substr($value->date, 5, 2);
    $day = substr($value->date, 8, 2);
    $date = $year . '/' . $month . '/' . $day;

    echo '<li><a href="' . $link . '" target="_blank">' . $date . ' ' . $title . '</a></li>';
}

javascript

	function HTML_Load(_html, replace) {

		var xmlhttp = new XMLHttpRequest();
		xmlhttp.open("GET", _html, true);
		xmlhttp.onreadystatechange = function () {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var data = xmlhttp.responseText;
				var elem = document.getElementById(replace);
				console.log(elem);
				elem.innerHTML = data;
				return data;
			}
		}
		xmlhttp.send(null);
	}
	HTML_Load('log.php', 'id-name'); //挿入したいid名