How to load post content on index page using ajax when post title in sidebar is clicked
I'm working on a new blog which display in a list, on sidebar, some categories and the posts of them. In the index page, in main content, I list some post titles from other category "New".
What I need is: when i click on one post link on sidebar to display in main content the post content via ajax or JQuery.
Answers 3
You will need to create a WordPress function that loads the post content and hook that into wp_ajax_nopriv. You will also need the jQuery ajax functions to send the $_POST data to your WordPress function via ajax and output the returned content in your empty div where you want it to display.
A simple approach would be to use the post ID in the class or id div tag so you can easily pull it out with jQuery.
Example using the sidebar code from Steven's answer:
Example jQuery (this should be in a separate file and enqueued using
wp_enqueue_script
so the the ajax url can be defined as a javascript namespace variable usingwp_localize_script
:Enqueue the script and set the ajax url variable:
Contents of the ajax.js file:
*Note: Add a loading animation graphic where the post will eventually display and and give it a div id of "loading-animation" and set it to display: none.
WordPress function to return the post content to the ajax call:
Just use something like this:
Then in your sidebar section, use something like this:
I think that is what you are looking for?
This answer is one of the best to explain the loading of post when selected from the side bar category and when the post is clicked on the post shows up but the posts can be target for either register/logged in or no-registered/public like:
I got a problem when i was using this but later figure this out by reading other WordPress ajax works.