Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress REST API 取得表示
export default function getRestApi () {
let $wppost = $('.wp-post ul');
if($wppost.length > 0) {
$.ajax({
url: 'https://koukitips.net/wp-json/wp/v2/posts?per_page=3&_embed'
}).then(
response => {
$.each(response, function(i, item) {
// title
let title = item.title.rendered;
//link
let link = item.link;
// Date
let date_data = new Date(item.date);
let year = date_data .getFullYear();
let month = date_data.getMonth() + 1;
let day = date_data.getDate();
let date = year + '/' + month + '/' + day;
// thum
let thum = '';
if(item._embedded['wp:featuredmedia']) {
thum = item._embedded['wp:featuredmedia'][0].source_url;
} else {
let content = item.content.rendered;
thum = content.replace(/.*<img src=\"(.*?)\"[\s\S]*/g, '$1');
}
let $dom =`
<li>
<div class="img"><a href="${link}" target="_blank" rel="noopener noreferrer"><img src="${thum}" alt="" /></a></div>
<p class="date">${date}</p>
<p class="title"><a href="${link}" target="_blank" rel="noopener noreferrer">${title}</a></p>
</li>
`;
$wppost.append($dom);
});
}, response => {
console.log('error: ', response);
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment