Rename image file name the same as post title in wordpress automatically?

Dopani

Well-known member
Registered
Joined
Mar 11, 2014
Messages
240
Points
18
Hi there,
Are there any ways to rename image file name the same as post title in wordpress automatically when I upload whatever a photo for my post? is it possible?
 

Marc0

Well-known member
Registered
Joined
Jun 6, 2012
Messages
890
Points
28
Hi there,
Are there any ways to rename image file name the same as post title in wordpress automatically when I upload whatever a photo for my post? is it possible?
If you are going to SEO for images on your wordpress blog then named your image file name according to your title post will get better for SEO and save your time on named file name for each image before upload them into your wordpress post.

Here's way to auto rename image file according to post title:

Open functions.php in theme directory and add this code

Code:
function wp_modify_uploaded_file_names($image_name) { 
    // Get the parent post ID, if there is one
    if( isset($_GET['post_id']) ) {
        $post_id = $_GET['post_id'];
    } elseif( isset($_POST['post_id']) ) {
        $post_id = $_POST['post_id'];
    } 
    // Only do this if we got the post ID--otherwise they're probably in
    //  the media section rather than uploading an image from a post.
    if(is_numeric($post_id)) {
 
        // Get the post slug
        $post_obj = get_post($post_id);
        $post_slug = $post_obj->post_name;
 
        // If we found a slug
        if($post_slug) {
 
            $random_number = rand(100,999999);
            $image_name['name'] = $post_slug . '-' . $random_number . '.jpg'; 
        } 
    } 
    return $image_name; 
}
add_filter('wp_handle_upload_prefilter', 'wp_modify_uploaded_file_names', 1, 1);
Codes above rename your image file name and add end of file with random number from 100 to 999999
There are any plugins to do this but you can use this code for fast and it don't consume more resource for your site.

Hope it helps!
 
Newer Threads
Replies
1
Views
2,971
Replies
6
Views
4,585
FDL
Replies
3
Views
3,474
Replies
29
Views
10,763
Replies
8
Views
5,199
Latest Threads
Replies
2
Views
60
Replies
2
Views
54
Replies
2
Views
111
Replies
4
Views
274
Recommended Threads

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top