Created
March 12, 2023 10:36
-
-
Save alefra88/7c6cff6c07d08620e9cea45babab6284 to your computer and use it in GitHub Desktop.
142. WordPress REST API y Fetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const d = document, | |
$site = d.getElementById("site"), | |
$posts = d.getElementById("posts"), | |
$loader = d.querySelector(".loader"), | |
$template = d.getElementById("post-template"), | |
$fragment = d.createDocumentFragment(), | |
DOMAIN = "https://malvestida.com", | |
SITE = `${DOMAIN}/wp-json`, | |
API_WP = `${SITE}/wp/v2`, | |
POSTS = `${API_WP}/posts?_embed`, | |
PAGES = `${API_WP}/pages`, | |
CATEGORIES = `${API_WP}/categories`; | |
function getSiteData() { | |
fetch(SITE) | |
.then((res) => (res.ok ? res.json() : Promise.reject(res))) | |
.then((json) => { | |
console.log(json); | |
$site.innerHTML = ` | |
<h3>Consumo de API Wordpress</h3> | |
<h2> | |
<a href="${json.url}" target="_blank">${json.name}</a> | |
</h2> | |
<p>${json.description}</p> | |
<p>${json.timezone_string}</p> | |
`; | |
}) | |
.catch((err) => { | |
console.log(err); | |
let message = err.statusText || "Ocurrió un error"; | |
$site.innerHTML = `<p>Error${err.status}:${message}</p>`; | |
}); | |
} | |
function getPosts() { | |
$loader.style.display = "block"; | |
fetch(POSTS) | |
.then((res) => (res.ok ? res.json() : Promise.reject(res))) | |
.then((json) => { | |
console.log(json); | |
json.forEach((el) => { | |
let $clone = $template.content.cloneNode(true); | |
$clone.querySelector(".post-image").src = | |
el._embedded["wp:featuredmedia"][0].source_url; | |
$clone.querySelector(".post-image").alt = el.title.rendered; | |
$clone.querySelector(".post-title").innerHTML = el.title.rendered; | |
$clone.querySelector(".post-author").innerHTML = ` | |
<img src= "${el._embedded.author[0].avatar_urls?.["48"] || ""}" alt="${ | |
el._embedded.author[0].avatar_urls?.["48"] || "" | |
}"> | |
<figcaption>${el._embedded.author[0].name}</figcaption> | |
`; | |
$fragment.appendChild($clone); | |
}); | |
$posts.appendChild($fragment); | |
$loader.style.display = "none"; | |
}) | |
.catch((err) => { | |
console.log(err); | |
let message = err.statusText || "Ocurrió un error"; | |
$posts.innerHTML = `<p>Error${err.status}:${message}</p>`; | |
$loader.style.display = "none"; | |
}); | |
} | |
d.addEventListener("DOMContentLoaded", (e) => { | |
getSiteData(); | |
getPosts(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment