Alright, so I have a related-posts.php script I wrote and I wish to insert it into posts only upon certain user action (scrolling). I also have a script file which is enqueued by wordpress and loads in footer – in there I’ve written ajax like so:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("relatedPosts").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/wordpress/wp-content/themes/mytheme/functions/widgets/ajaxa.php",true);
xmlhttp.send();
AJAX loads the file, however the problem is: the php script seems to be ‘unaware’ of the page it loads in since
global $post;
print_r($post);
outputs 0 (zero)…
I understand there’s a proper way of using ajax in wordpress however all the documentation I found relies heavily on Jquery (which I don’t know nor wish to learn at the moment)
How can I make it work using javascript solely?
Your PHP code is unaware of the global $post object because it is not compiled with the rest of the page – you need to think of these as two separate pages that do not share objects in PHP unless they are saved in the session since they are compiled independently.
If you want to find related posts, you should pass the id of the main post to the PHP script generating the associations, then use that to look up the related items within ajax.php… e.g.
Then in ajaxa.php something like…
to get the value passed from the HTML page.