0

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.

  • No, not really. Not the way you've attempted at least. Could you include more information and code about this image button, and how it's handled, and where you want this filter to work? – Jacob Peattie Jun 14 '19 at 15:49
  • I get the click on this id="a" button, so I know that the "a button" is pressed and, when the media uploader appears and I upload an image, the function save_landscaped_version_of_img triggers because I've added the function to the wp_handle_upload via Ajax... But it doesn't work.... – AmintaCode Jun 14 '19 at 15:56
  • 1
    it sounds like this is an XY problem, where your question is about Y, which is a solution you've devised for a problem X you've not mentioned. Can you tell us what you were originally trying to do and what the problem was that pushed you to devise this solution you're trying to fix? Also can you explain what these buttons are? It's not clear what you're referring to or what the fields you mention are, or where save_landscaped_version_of_img comes from or what it does. Please update your question and assume we know nothing – Tom J Nowell Jun 14 '19 at 16:12
  • I think I figured out what you're trying to ask, and now understand why it doesn't make sense to other people. You're asking if you can unhook something on a request so that when the next request happens the behaviour is different. I've left an answer explaining why that isn't possible ( that's not how PHP/WP work ) – Tom J Nowell Jun 14 '19 at 17:04
2

Is 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.