How to tie built in AJAX to an add_action?

I found a way around this by not using the JS methods themselves but basically listening for their attached AJAX calls and taking it from there. This was my final code. I used the the QueryStringToHash function listed here to parse the data sent in the first place, and use this to determine if I wanted to proceed with refreshing the media frame content view. This was achieved with the help of this post. The one downfall of this method is that once this has been executed, the media library will no longer update with new uploads automatically.

functions.php

add_action('admin_footer-post.php', 'reload_attachments');
add_action('admin_footer-post-new.php', 'reload_attachments');

function reload_attachments() {
    ?>
    <script>
        jQuery(function($) {
            $('#wpcontent').ajaxComplete(function(a,b,c) {
                var input = QueryStringToHash(c.data);
                if (input.action == "save-attachment" || input.action == "save-attachment-compat") {
                     if (wp.media.frame.content.get()!==null) {
                        wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())});
                        wp.media.frame.content.get().options.selection.reset();
                     } else {
                        wp.media.frame.library.props.set({ignore: (+ new Date())});
                     }
                }
            });
        });
    </script>
    <?php
}

There are probably better ways to enqueue this script but actually – as @Svetoslav Marinov comments above – there are perhaps better ways of solving my issue without the inclusion of meta data, so this work is resigned to the cutting room floor. Hopefully someone finds it useful.

Leave a Comment