1

Best regards, I want to change the name of the automatic image with the title of the post.

For example, I have the image called 1231231252345.jpg and Title of the article is "Article for a test", I want to change the name of the image in "article-for-a-test.jpg"

2

I think what you're looking for is the filter: wp_handle_upload_prefilter.

From the Codex:

The single parameter, $file, represent a single element of the $_FILES array. The wp_handle_upload_prefilter provides you with an opportunity to examine or alter the filename before the file is moved to its final location.

Example code from the Codex:

add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );

function custom_upload_filter( $file ){
    $file['name'] = 'wordpress-is-awesome-' . $file['name'];
    return $file;
}

How to use this hook

add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ) {
    if ( ! isset( $_REQUEST['post_id'] ) ) {
        return $file;
    }
    $id           = intval( $_REQUEST['post_id'] );
    $parent_post  = get_post( $id );
    $post_name    = sanitize_title( $parent_post->post_title );
    $file['name'] = $post_name . '-' . $file['name'];
    return $file;
}
  • No, what I need is to rename the image name by the post name.. not to "wordpress-is-awesome-".. – Bursuc Andrei Apr 12 at 7:37
  • That's just an example from the codex of the hook you need to use. I've updated my answer with a practical use of that hook. – MikeNGarrett Apr 12 at 13:28
  • I did this already but still not working. It keeps the image name. It doesn't take the post name – Bursuc Andrei Apr 12 at 13:57
  • That's on you, mate. It works for me. – MikeNGarrett Apr 12 at 14:17
  • Actually it's working, the problem is that it keeps the old name after the post title. Example. Post title - "1234", and the image is 1234-1234-old-image-name.jpg – Bursuc Andrei Apr 12 at 14:19

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.