Utilizing ajax for loading a new post in WordPress is quite simple. Below is the basic code snippet to achieve this:
function loadNewPost(){
var menuitem = document.getElementsByTagName('nav')[0].childNodes;
for(var i= 0; i < menuitem.length; i++)
{
bindEvent(menuitem[i], "click", loadAjax);
}
};
function loadAjax (event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
var content = document.getElementsByTagName('article')[0];
if(xhr.readyState == 4){
if(xhr.status == 200) {
content.innerHTML = xhr.responseText;
} else{
content.innerHTML = 'Failed to establish connection with the server. Please check your internet connection.'
}
}
};
xhr.open('GET', this.href, true);
xhr.send();
}
bindEvent(window, "load", loadNewPost);
The above code functions well but loads the entire new post along with menu, header, and footer elements. I am interested only in extracting the main content and comments. Is there any way to specifically request these specific contents from WordPress using ajax? Or do I have to retrieve the entire page and then filter out the required content before displaying it?
Perhaps creating a custom template page could be a solution. However, I am unsure how to implement this. Any guidance on configuring that would be appreciated.
I hope my query was clear. It's my first attempt at developing a WordPress theme using PHP.
Thank you for your assistance!