We have a plugin that allows us to manage custom post types and we’d like to add AJAX functionality in saving, editing, and deleting posts. I couldn’t find similar problems in the internet so I’m wondering if this isn’t something easily doable?
Leave a Reply
You must be logged in to post a comment.
You can technically make a XHR to post.php via JavaScript. Below is a proof-of-concept for saving/editing posts only. I haven’t tested it at all, so I’m sure you will need to tweak it. I wanted to give you a basic workflow for accomplishing something like this. You can take it and run with it if you need to extend it.
Step 1: Add AJAX handler to admin_head for new and existing posts.
Step 2: Hook into the save_post action.
This runs after the post has been saved to the database, so you can save whatever postmeta you need and halt the page render.
The only major caveat I can see is that you will need to refresh nonces on the page somehow via XHR.
For deleting a post, I’m not sure why you would want to use AJAX when it’s a simple click of a link that does the job already. Deleting a page in every case will send you to another page, namely, edit.php. This defeats the purpose of using AJAX which is to keep everything asynchronous on one page load.
Hope this helps you out.
Brian Fegter’s response was the right idea, but it had a few bugs. Here’s a more polished solution based on the same principle.
Step 1: PHP Logic.
Place in functions.php (or a plugin file)
Step 2: Create javascript in an external file
Brian’s solution of echoing out the js directly on to the page works too.
Step 3: Enqueue your javascript file
If you echoed it out (like Brian), you don’t have to do this. I prefer this method because it allows us to dequeue the script, localize variables, and adjust script load order easily.
This snippet does not address nonces. Anyway, I hope that helps someone.
Here’s a more polished solution 😉
Also i make it shorter for easy to use 🙂 just put this code in your functions.php: