Last active
September 2, 2024 01:22
-
-
Save alefra88/145a0ea0b8826c75121b7fc685963188 to your computer and use it in GitHub Desktop.
Codigo js de la clase 141 wordpress API rest 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; | |
$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