I'm trying to bind a function to a filter hook via Ajax, like that:
function ajax_called_function_contains() {
add_filter( 'wp_handle_upload', 'save_landscaped_version_of_img' );
};
The goal is to call the wp_handle_upload
only when I click an "add image button" on a given field, so the save_landscaped_version_of_img
function triggers on wp_handle_upload
hook but only after I've clicked the "add image button" on that given field.
I'm trying to bind a function to a filter hook via Ajax, like that:
function ajax_called_function_contains() {
add_filter( 'wp_handle_upload', 'save_landscaped_version_of_img' );
};
The goal is to call the wp_handle_upload
only when I click an "add image button" on a given field, so the save_landscaped_version_of_img
function triggers on wp_handle_upload
hook but only after I've clicked the "add image button" on that given field.
1 Answer
Reset to default 2Is it possible to bind a function to a filter hook via Ajax?
No, because page requests are self contained.
When you request something from PHP, everything gets loaded from a fresh clean slate. At the end of the request, that slate is discarded.
This is different from say a Node application that is always running.
So, if you make an AJAX request and unhook a filter, it's only unhooked for that request. A second page load, or AJAX request will not be affected by the unhooking, so it would need to be done on every request.
If you want something to persist across requests, you need to store it somewhere that persists, such as the database of the filesystem. Either way what you want to do won't work, and there's no change to WordPress or PHP you could make that would allow it to work the way you proposed.
click
on thisid="a"
button, so I know that the "a button" is pressed and, when the media uploader appears and I upload an image, the functionsave_landscaped_version_of_img
triggers because I've added the function to thewp_handle_upload
via Ajax... But it doesn't work.... – AmintaCode Commented Jun 14, 2019 at 15:56save_landscaped_version_of_img
comes from or what it does. Please update your question and assume we know nothing – Tom J Nowell ♦ Commented Jun 14, 2019 at 16:12