Emailing on Image Attachment Uploads

Sometimes it’s useful to know when an image or audio attachment is added. Here I’ll outline how to send an emailwhen it happens.

How It Works

We start by hooking into add_attachment, and grabbing the user IDs of all administrators:

    // send to admins of the current blog/site
    $args = array();
    $args[0] = 'user_email';
    $wp_user_search = new WP_User_Query( array( 'role' => 'administrator','fields' => $args ) );

We then add each admin to an array of recipients, and if we’re on multisite, repeat for super administrators using get_super_admins.

Finally, we check if any recipients were added, and if so, we put an email together, and send to each administrator:

    // send the email
    if(empty($recipients)){
        // there is nobody to send this to? Abort!
        return;
    }
    $admin_email = get_option('admin_email');
    $headers= "From:$admin_email\r\n";
    $headers .= "Reply-To:$admin_email\r\n";
    $headers .= "X-Mailer: PHP/".phpversion()."\r\n";
    $headers .= "content-type: text/html";

    $subject = 'New Attachment uploaded';
    $template = 'New attachment uploaded to WordPress with the ID: '.$att_id.'.'. wp_get_attachment_link( $att_id,'',true,false,'click here to view this attachment' );
    foreach($recipients as $to){
        @wp_mail($to, $subject, $template, $headers);
    }

The Code

View the code on Gist.

Things To Try

You could take out the part with the super administrators, or change the user role to send notifications to editors, or even modify the $template variable to add styling.

One thought on “Emailing on Image Attachment Uploads

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.