Welcome to EasyCodingWithAI!

Before you dive into coding with AI, take a moment to consider some valuable insights. Our articles cover the pros and cons of using AI in development, the importance of having a development environment, and how AI empowers hobbyists and small businesses:

Post Icon

Tutorial : WordPress – Automatically Rename Images On Upload.

Posted by Richard Robins on October 26, 2024 - Last modified on October 30, 2024.

Overview

This plugin automatically renames uploaded images to match the post title, ensuring clean and consistent filenames. It also sets appropriate alt text and image titles, enhancing SEO and accessibility.

Example Prompt.

Help me create a WordPress plugin that automatically renames images when they are uploaded to match the post title. The plugin should filter the filename to remove special characters and convert it to a URL-friendly format. If the post title is empty or set to “Auto Draft,” the plugin should use a default naming convention. Additionally, the plugin should update the image’s alt text and ensure the links in the post content are updated to reflect the new image filenames.

Setup Steps

Step 1: Create the Plugin Directory

  1. Navigate to Your WordPress Installation: Go to the wp-content/plugins directory of your WordPress installation.
  2. Create a New Folder: Create a folder named easycoding-automatically-rename-images-on-upload.

Step 2: Create the Main Plugin File

  1. Create a PHP File: Inside the newly created folder, create a file named easycoding-automatically-rename-images-on-upload.php.

Step 3: Implement the Plugin Functionality

  1. Add the Code: Copy and paste the following complete code to implement the functionality:

<?php
/*
Plugin Name: EasyCodingWithAI - Automatically Rename Images On Upload
Description: Automatically renames images to match post title field.
Version: 1.3
Author: EasyCodingWithAI
*/

function easycoding_filter_filename($title) {
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', $title);
$title = str_replace(' ', '-', $title);
$title = strtolower($title);
return $title;
}

function easycoding_rename_image_on_upload($file) {
$default_title = 'untitled-image';
$alt_text = 'Untitled Image'; // Default alt text

if (isset($_POST['post_id']) && $post_id = (int)$_POST['post_id']) {
$post = get_post($post_id);

// Initialize variables
$title = '';
$new_filename = '';

// Check if post exists
if ($post) {
$title = $post->post_title;

// Check if the title is empty or "Auto Draft"
if (empty($title) || strtolower($title) === 'auto draft') {
// Use default title and alt text
$new_filename = 'image-' . $post_id . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
} else {
// Set the filtered title for the filename
$filtered_title = easycoding_filter_filename($title);
$new_filename = $filtered_title . '-' . $post_id . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
}
} else {
$new_filename = 'image-' . $post_id . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
}

// Set the new filename
$file['name'] = $new_filename;

// Set alt text and title for untitled images
if (empty($title) || strtolower($title) === 'auto draft') {
add_filter('wp_handle_upload', function($upload) use ($alt_text) {
// Set alt text for the image in meta after upload
add_post_meta($upload['id'], '_wp_attachment_image_alt', $alt_text);
return $upload;
});

// Set the post title to "Untitled Image"
add_action('add_attachment', function($attachment_id) {
wp_update_post(array(
'ID' => $attachment_id,
'post_title' => 'Untitled Image' // Set title to "Untitled Image"
));
});
}
}

return $file;
}
add_filter('wp_handle_upload_prefilter', 'easycoding_rename_image_on_upload');

function easycoding_set_image_meta($post_ID) {
$post = get_post($post_ID);

if ($post && $post->post_type == 'attachment') {
$parent_id = $post->post_parent;
$parent_post = get_post($parent_id);

if ($parent_post) {
$base_title = easycoding_filter_filename($parent_post->post_title);
$attachments = get_posts(array(
'post_type' => 'attachment',
'post_parent' => $parent_id,
'orderby' => 'ID',
'order' => 'ASC'
));

$index = array_search($post_ID, array_column($attachments, 'ID')) + 1;

// Update alt text
if (empty($parent_post->post_title) || strtolower($parent_post->post_title) === 'auto draft') {
$alt_text = 'Untitled Image #' . $index; // Set alt text for untitled images
} else {
$alt_text = ucwords(str_replace('-', ' ', $base_title)) . " #$index"; // Use the base title with an index
}
update_post_meta($post_ID, '_wp_attachment_image_alt', $alt_text);

// Update the title with a readable format
wp_update_post(array(
'ID' => $post_ID,
'post_title' => $alt_text
));
}
}
}
add_action('add_attachment', 'easycoding_set_image_meta');

function easycoding_update_image_title_and_urls($post_id) {
$post = get_post($post_id);

if ($post && $post->post_type != 'attachment') {
$attachments = get_posts(array(
'post_type' => 'attachment',
'post_parent' => $post_id
));

foreach ($attachments as $attachment) {
$old_url = wp_get_attachment_url($attachment->ID);

$filtered_title = easycoding_filter_filename($post->post_title);
$ext = pathinfo($attachment->guid, PATHINFO_EXTENSION);
$attachment_id = $attachment->ID;

// Use title-attachment ID format for the filename
$new_filename = $filtered_title . '-' . $attachment_id . '.' . $ext; // Use title-attachment ID format
$upload_dir = wp_upload_dir();
$new_url = trailingslashit($upload_dir['url']) . $new_filename;

// Update alt text and title if the title is set
if (!empty($filtered_title) && strtolower($filtered_title) !== 'auto draft') {
$alt_text = ucwords(str_replace('-', ' ', $filtered_title));
} else {
$alt_text = 'Untitled Image'; // Set alt text for untitled images
}

update_post_meta($attachment->ID, '_wp_attachment_image_alt', $alt_text);
wp_update_post(array(
'ID' => $attachment->ID,
'post_title' => $alt_text,
));

// Update GUID
$post_content = $post->post_content;
$updated_content = str_replace($old_url, $new_url, $post_content);
if ($updated_content !== $post_content) {
wp_update_post(array(
'ID' => $post_id,
'post_content' => $updated_content
));
}
}
}
}
add_action('save_post', 'easycoding_update_image_title_and_urls');

function easycoding_rename_auto_draft_images($post_id) {
// Check if the post is being updated
if (get_post($post_id) && get_post($post_id)->post_type != 'attachment') {
$post = get_post($post_id);
$new_title = easycoding_filter_filename($post->post_title);
$default_title = 'untitled-image';

// Only proceed if the post title is not empty or "Auto Draft"
if (empty($new_title) || strtolower($new_title) === 'auto draft') {
$new_title = $default_title;
}

$attachments = get_posts(array(
'post_type' => 'attachment',
'post_parent' => $post_id,
'numberposts' => -1,
'post_status' => 'any'
));

foreach ($attachments as $attachment) {
$old_filename = $attachment->guid; // Get the old filename
// Check if the filename starts with 'image-' and contains the attachment ID
if (strpos($old_filename, 'image-') === 0) {
$ext = pathinfo($old_filename, PATHINFO_EXTENSION); // Get the file extension
// Construct the new filename
$new_filename = 'image-' . $attachment->ID . '.' . $ext;

// Update the attachment's GUID
$upload_dir = wp_upload_dir();
$new_url = trailingslashit($upload_dir['url']) . $new_filename;

// Update the post meta and attachment details
wp_update_post(array(
'ID' => $attachment->ID,
'guid' => $new_url,
'post_title' => ucwords(str_replace('-', ' ', $new_title)),
));

// Optionally, rename the physical file (if needed)
rename($old_filename, $new_url);
}
}
}
}
add_action('save_post', 'easycoding_rename_auto_draft_images');

Step 4: Activate the Plugin

  1. Log in to Your WordPress Admin Dashboard: Go to Plugins > Installed Plugins.
  2. Find Your Plugin: Locate “EasyCodingWithAI – Automatically Rename Images On Upload” in the list.
  3. Activate the Plugin: Click the Activate link.

Richard Robins

Richard Robins

Richard is passionate about sharing how AI resources such as ChatGPT and Microsoft Copilot can be used to create addons and write code, saving small website owners time and money, freeing them to focus on making their site a success.


Disclaimer

The coding tips and guides provided on this website are intended for informational and educational purposes only. While we strive to offer accurate and helpful content, these tips are meant as a starting point for your own coding projects and should not be considered professional advice.

We do not guarantee the effectiveness, security, or safety of any code or techniques discussed on this site. Implementing these tips is done at your own risk, and we encourage you to thoroughly test and evaluate any code before deploying it on your own website or application.

By using this site, you acknowledge that we are not responsible for any issues, damages, or losses that may arise from your use of the information provided herein.