Howdi,

I am trying to fire some code that will occur when I save an image in the media library, as per usual, I select the file, upload, enter the meta data and then click save. At this point I want to hook into wordpress, and redirect wordpress to another URL. This is so that rather than taking the user to a list of uploaded media, I can then take them to an image manipulation tool instead.

I found a filter that fires just before the meta data is created, but nothing for when the file is saved?

Thanks,

3 s
3

Actually there are no hook fired after media file(s) upload, at least as far as I know. The problem with the hooks available along the way of uploading and saving media files and data is that they are limited to one portion of the process, and so using any of them is not reliable. For example, add_attachment is fired after a new file completed the upload process before editing the file metadata, and if you intend to redirect the user at this point, it will break the upload process for subsequent files if we have more than one file upload, it might be suitable though for other kinds of actions.

For your specific case however, you can hook to admin_init action hook and check if we are on media library screen after we have uploaded or edited file, we know that by saving the number of attachments before upload and compare it agianst the number of attachments after the upload:

add_action('admin_init', 'redirect_after_media_save');
function redirect_after_media_save() {

    global $pagenow;

    // when visiting the upload screen, we save the number of attachments
    if ( $pagenow == 'media-new.php' ) {
        $attachments_before = array_sum((array)wp_count_attachments());
        update_option('count_attach_before', $attachments_before);
    }

    if ( $pagenow == 'upload.php' ) { // we are on media library page

        // get attachments count before and after upload
        $attachments_before = get_option('count_attach_before');
        $attachments_after = array_sum((array)wp_count_attachments());

        if ( 
            // there are new files uploaded
            ( wp_get_referer() == admin_url('media-new.php') && $attachments_after > $attachments_before )
            ||
            // or we have just edited media file
            isset($_GET['posted'])
        ) {
                // redirect to desired location
                wp_redirect(admin_url());
                exit;
        }
    }
}

This code will redirect the user to dashboard after successful upload or edit of media file, you can adjust it to suit your need. You may also want to choose admin hook other than admin_init if you wish to perform tasks other than redirection.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *