I’m trying to hook into the “save_post” action from an AJAX callback in my plugin, but it doesn’t seem to work. In fact, hooking into “save_posts” only seems to work from a few key action execution points (e.g. “init” or “admin_init”) but not from others (e.g. an “add_meta_boxes” callback).
In my particular case, I’d like to click a button on the Edit Post screen to add a new custom metabox, and have it save the metabox’s data properly. But of course by the time I click that button and add that metabox, I’ve already hooked the “save_post” action once and WP seemingly doesn’t want to let me hook it again.
Looking briefly through the WP source code, I don’t see any obvious reasons why I shouldn’t be able to hook that action again. Any ideas how to work around this apparent limitation, or at least an explanation as to why it’s not working?
Adding function to hooks is runtime operation, it is not persistent. Whatever hook operation you run in Ajax actions – they are performed in separate WP instance and expire as soon as Ajax response is returned. They have no influence on currently loaded page.
You probably need to hook your functionality to
save_post
as usual (not in Ajax action) and check for your additional metabox to handle it.I was literally banging my head around a related issue and this is the first thing I’ve read online that gave a solid pointer to what I was doing wrong.
Turns out
add_meta_boxes
is called later thansave_post
, so you’d need to set up the save hook BEFORE the metabox is created. Seems counter-intuitive at first, but the markup is typically generated AFTER WordPress goes through it’s processing, so it makes sense that the hooks are being set up before the metabox is rendered.Thankfully I had a bit of code that tied into the
admin_init
hook, which fires off beforesave_post
so it became really easy to fix the problem at hand.Once again, thanks for posting this question. It wasn’t exactly what I was looking for but it hinted at the answer to the problem.