plugin development – wp.media gallery collection sometimes undefined

Question

I have a function that includes an external image-source into the media-library (wp-admin/upload.php), by making an ajax-call to said image-source, formatting the response appropriately and inserting each image into the library with this function:

wp.media.frame.content.get('gallery').collection.add(formatted);

This works really well for me – most of the time.
For whatever reason, sometimes i get this exception in the debugger and the images are not added:

jQuery.Deferred exception: Cannot read properties of undefined (reading ‘add’) TypeError: Cannot read properties of undefined (reading ‘add’) at addImages

It only happens maybe every 20th-30th reload, and even then it is not consistent. Sometimes the initial load works fine, but on loading more images it does not work, or the other way around.

I tried looking at it in the debugger, and wp.media.frame.content.get('gallery') is fine, just collection is undefined.

In my PHP, on wp_enqueue_script I have ['media', 'media-grid', 'media-editor', 'media-views', 'jquery'] as dependencies, am I maybe missing one here?
But even if – why would it sometimes work on initial load but not on loading more (or vice-versa)?

(WordPress Version 5.8.1)

0
devssc 1 month 2021-12-14T03:04:18-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse