function learningWorpress_resources() {
wp_enqueue_style('style',get_stylesheet_uri())
wp_enqueue_script ('main_js', get_templete_directory_uri() .'/js/main.js',NULL, 1.0 , true )
}
add_action ('wp_enqueue_scripts','learningWordpress_resources');
-------
main.js
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function() {
//Standard Ajax code from Codepen
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://localhost:8888/wordpress/wp-json/wp/v2/posts');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
});
}
//Pulls data from above function
function createHtml(postsData) {
var ourHTMLString = '';
for(i = 0; i < posts.Data.length; i++) {
ourHTMLString +='<h2>' + postsData[i].title.rendered + '</h2>';
ourHtmlString += postsData[i].content.rendered;
}
// insert the html into the required div
protfolioPostsContainer.innerHTML = ourHtmlString ;
}
<button id="protfolio-posts-btn"> load </button>
<div id="portfolio-posts-container"> </div>
......