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?

2 Answers
2

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.

Leave a Reply

Your email address will not be published. Required fields are marked *