I trying to program the following rules:

  1. When attachment uploaded on wp-admin/post.php page, on the act of uploading, rename it to {post-slug}-{n}-[WxH].{ext}
  2. When attachment uploaded on wp-admin/upload.php page, on the act of uploading, rename it to {site-name}-{n}-[WxH].{ext}

Where {n} is the numerical order, [WxH] the sizes applied by WordPress and {ext} its extension.

Item 1 I got with add_attachment hook. How can I achieve item 2? How to change the name of a file uploaded on Media Page on the act of uploading?


The best way of doing this might be to attach a custom field to each post to keep the increment {n}.

Something to the effect of:

$attach_inc = 1;

if ( is_single() ) {
    if ( $attach_inc = get_post_meta( $post_id, 'attachment_inc', true ) ) {
        update_post_meta( $post_id, 'attachment_inc', $attach_inc );
    } else {
        add_post_meta( $post_id, 'attachment_inc', $attach_inc );
} else {
    if ( $attach_inc = get_option( 'attachment_inc' ) ) {
        set_option( 'attachment_inc', $attach_inc );
    } else {
        add_option( 'attachment_inc', $attach_inc );

  • Thanks, socki03, the incrementing part I'm gonna solve creating a meta field for the post and a config fild for the site, but the problem is which action to hook. Oct 20 '16 at 15:13
  • I misunderstood your last sentence in your question then. I thought you'd figured out how to change the name using add_attachment, so I thought you were looking for ideas how to increment attachment IDs.
    – socki03
    Oct 20 '16 at 15:59

I suppose you could change the filename trough wp_handle_upload_prefilter. Though I'm not sure how you are going to determine if it's a post upload or media upload, maybe you can check the $post global.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.