Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Last active March 9, 2023 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhowellsmead/bd2f864aafb278dd043c79a23afd7bb3 to your computer and use it in GitHub Desktop.
Save markhowellsmead/bd2f864aafb278dd043c79a23afd7bb3 to your computer and use it in GitHub Desktop.
First example of GitHub Copilot. Gets posts from the WordPress REST API and appends them to the postContainer.
// get the current site's REST API base url
const restApiBaseUrl = wpApiSettings.root;
// get the element with the class name '.posts-container' from the document
const postsContainer = document.querySelector('.posts-container');
// use restApiBaseUrl to get all of the posts from the rest api in a recursive async function. wrap the function in an IIFE.
// append the posts to the posts container as objects. add a class name to each element using the classNameBase 'shp-my-posts' and the post id.
(async function getPosts() {
// stop processing if there is no posts container
if (!postsContainer) {
return;
}
// add a class name to each element using the classNameBase 'shp-my-posts' and the post id.
const classNameBase = 'shp-my-posts';
const posts = await fetch(`${restApiBaseUrl}wp/v2/posts`).then(response => response.json());
posts.forEach(post => {
const postElement = document.createElement('div');
postElement.classList.add(classNameBase, `${classNameBase}-${post.id}`);
postElement.innerHTML = `
<h2>${post.title.rendered}</h2>
<div>${post.content.rendered}</div>
`;
postsContainer.appendChild(postElement);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment