Skip to content

Instantly share code, notes, and snippets.

@Qubadi
Last active March 15, 2025 20:50
Show Gist options
  • Save Qubadi/e245e954d8dd3e2357e923ede5df8aaa to your computer and use it in GitHub Desktop.
Save Qubadi/e245e954d8dd3e2357e923ede5df8aaa to your computer and use it in GitHub Desktop.
JetFormbuilder: Rename uploaded image filename and title based on post title
The JetFormBuilder custom code automatically changes the uploaded image filename and title based on the post title.
It also supports multiple image uploads as well as meta field media, such as galleries, etc.
Here’s what you need to do first (no need to change anything in the code):
Create a post action in the JetFormBuilder form, select "Call Hook", and name it: image_title.
IMPORTANT: MAKE SURE YOU ADD THE CALL HOOKS ACTION AT THE BOTTOM AND NOT AT THE TOP.
Copy the following PHP and create a PHP snippet using your snippet plugins.
Paste the code into the plugin and save it.
__________________________________________________________
/**
* JetFormBuilder - Rename uploaded images to match post title
* Fully supports multiple images per field (post thumbnail, meta fields, attachments) with security enhancements.
*/
// Fix: Remove 'unnamed-file' from all uploaded filenames BEFORE they are saved
add_filter( 'sanitize_file_name', function( $filename ) {
$filename = str_replace( array('.unnamed-file', '-unnamed-file', 'unnamed-file'), '', $filename );
return $filename;
}, 10 );
// Prevent direct file access
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Rename uploaded images based on post title, handling multiple images per field securely.
*/
function jfb_rename_attachments_after_insert( $post_id, $settings = array() ) {
$post_id = absint( $post_id );
if ( empty( $post_id ) ) {
return;
}
// Verify user capabilities for security
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
// Get the post and ensure it's valid
$post = get_post( $post_id );
if ( ! $post || is_wp_error( $post ) ) {
return;
}
// Generate new filename base from post title
$new_base_name = sanitize_title( $post->post_title );
if ( empty( $new_base_name ) ) {
return; // No renaming if title is empty
}
// 1 **Find all standard post attachments**
$attachments = get_attached_media( 'image', $post_id );
// 2 **Include the featured image if not already in attachments**
$thumbnail_id = get_post_thumbnail_id( $post_id );
if ( $thumbnail_id ) {
$thumb = get_post( $thumbnail_id );
if ( $thumb && ! is_wp_error( $thumb ) ) {
$attachments[ $thumbnail_id ] = $thumb;
}
}
// 3 **Find images stored in JetFormBuilder meta fields dynamically**
$meta_data = get_post_meta( $post_id );
foreach ( $meta_data as $key => $value ) {
if ( is_array( $value ) ) {
foreach ( $value as $meta_value ) {
if ( is_numeric( $meta_value ) ) {
$attachments[ $meta_value ] = get_post( $meta_value );
} elseif ( is_string( $meta_value ) && strpos( $meta_value, ',' ) !== false ) {
// Handle multiple image IDs in a single field (gallery)
$image_ids = array_map( 'trim', explode( ',', $meta_value ) );
foreach ( $image_ids as $image_id ) {
if ( is_numeric( $image_id ) ) {
$attachments[ $image_id ] = get_post( $image_id );
}
}
}
}
} elseif ( is_numeric( $value ) ) {
$attachments[ $value ] = get_post( $value );
}
}
// 4 **Rename all detected images with unique numbers**
$used_filenames = [];
$image_counter = 1;
foreach ( $attachments as $attachment ) {
if ( ! is_object( $attachment ) || ! isset( $attachment->ID ) ) {
continue;
}
$attachment_id = absint( $attachment->ID );
if ( ! $attachment_id ) {
continue;
}
$current_file = get_attached_file( $attachment_id );
if ( ! $current_file || ! file_exists( $current_file ) || ! is_writable( $current_file ) ) {
continue;
}
$path_parts = pathinfo( $current_file );
$upload_dir = wp_upload_dir();
if ( strpos( $current_file, $upload_dir['basedir'] ) !== 0 ) {
continue;
}
$dir = trailingslashit( $path_parts['dirname'] );
$ext = isset( $path_parts['extension'] ) ? '.' . sanitize_file_name( $path_parts['extension'] ) : '';
// Generate a unique filename with an auto-incremented number
do {
$new_filename = $new_base_name . '-' . $image_counter . $ext;
$new_file_path = $dir . $new_filename;
$image_counter++;
} while ( file_exists( $new_file_path ) );
$used_filenames[] = $new_filename;
if ( $new_file_path === $current_file ) {
continue;
}
if ( ! is_writable( $dir ) ) {
continue;
}
if ( ! @rename( $current_file, $new_file_path ) ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( sprintf( 'Failed to rename file from %s to %s', esc_html( $current_file ), esc_html( $new_file_path ) ) );
}
continue;
}
$relative_path = _wp_relative_upload_path( $new_file_path );
$updated_post = array(
'ID' => $attachment_id,
'post_title' => esc_attr( $post->post_title ),
'post_name' => esc_attr( $new_filename ),
'guid' => set_url_scheme( $upload_dir['baseurl'] . '/' . $relative_path )
);
wp_update_post( $updated_post );
update_post_meta( $attachment_id, '_wp_attached_file', $relative_path );
wp_update_attachment_metadata( $attachment_id, wp_get_attachment_metadata( $attachment_id ) );
clean_attachment_cache( $attachment_id );
}
wp_cache_flush();
}
/**
* Hook after post is inserted
*/
add_action( 'jet-form-builder/form-handler/after-insert', 'jfb_hook_after_insert', 99, 2 );
function jfb_hook_after_insert( $post_id, $settings ) {
jfb_rename_attachments_after_insert( $post_id, $settings );
}
/**
* Custom action hook implementation
*/
add_action( 'jet-form-builder/custom-action/image_title', 'jfb_trigger_rename_for_custom_action', 10, 2 );
function jfb_trigger_rename_for_custom_action( $request_data, $handler ) {
if ( ! is_object( $handler ) || ! isset( $handler->response_data ) || ! is_array( $handler->response_data ) ) {
return;
}
$post_id = isset( $handler->response_data['inserted_post_id'] ) ? absint( $handler->response_data['inserted_post_id'] ) : 0;
if ( $post_id ) {
jfb_rename_attachments_after_insert( $post_id );
}
}
/**
* Extra hook for safe measure - runs later in the process
*/
add_action( 'jet-form-builder/post-type/after-all-actions', 'jfb_final_rename_attachments', 99, 2 );
function jfb_final_rename_attachments( $post_id, $action_handler ) {
jfb_rename_attachments_after_insert( absint( $post_id ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment