Question

I have a custom form for publishing posts. When the new post is first created, there is no existing post ID, so attaching photos to the post doesn't work until after the post is saved and an ID is generated for the post.

The first thing I've done is initiate an auto-save so that a post ID is generated to represent the new post. However, I'm can't figure out how to update the wp.media object with this new ID so that uploaded posts are assigned to the ID generated during the auto-save.

Is there a way to reinitialize the wp.media object with the new post ID?

edit

I found this resource, but it doesn't seem to cover how to assign an post ID, and I can't seem to locate it in the source code referenced by the git either...

https://github.com/thomasgriffin/New-Media-Image-Uploader/blob/master/js/media.js

update

Looks like I was able to reassign the post ID to the wp.media object by simply doing this:

wp.media.model.settings.post.id = new_id;

However, I'm experiencing some permission issues now. As an admin, everything works fine, but as any other user, I get an error "An error occurred in the upload. Please try again later."

Uploading works fine with all users once the post is saved, but for some reason it won't allow me to upload with non-admin users after assigning a new id to the wp.media object.

R

Was it helpful?

Solution

Finally sorted it out.

AJAX is used to initiate the auto-save in the background while the user edits the post. When the auto-save ID is returned, it's re-assigned to the wp.media object like this:

wp.media.model.settings.post.id = autos_save_id;

The permission issue I was experiencing came from the simple fact that my user role didn't have the 'edit_post' capability. Duh.

OTHER TIPS

If I remember correct the media has an ID just like post/pages. It is up to the editor/system to associate media to post.

When I upload an image (media) to my local dev I edit it via :

site.com/wp-admin/post.php?post=19&action=edit

Where 19 is the media ID.

if I go to site.com/?p=19 I am forwarded to site.com/?attachment_id=19 and get to see the media.

Regarding the post/page (custom form) - when implemented correctly, on first save (submit) the post gets an ID. That ID remains the same. (beware of autosave post IDs and similar).

Tell me more about what you know regarding the "wp.media object" or let me know if I missed something?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top