You can hook onto add_attachment
and force the slug to work off the filename like so:
Update: To uppercase the slug, you’ll need to add a temporary filter onto wp_unique_post_slug
. You can’t simply use strtoupper( $slug )
as WordPress sanitises (lowercases) it within the update function.
/**
* Force attachment slug to ignore title from metadata (if any).
*
* @link http://wordpress.stackexchange.com/q/140132/1685
*
* @param int $post_id
*/
function wpse_140132_attachment_slug_as_file_name( $post_id ) {
if ( $post = get_post( $post_id ) ) {
if ( $file = get_attached_file( $post->ID ) ) {
// Get file name, without extension.
$slug = pathinfo( $file, PATHINFO_FILENAME );
// Only update if different to current slug!
if ( $slug && $slug != $post->post_name ) {
add_filter( 'wp_unique_post_slug', 'wpse_140132_attachment_slug_as_file_name_uppercase', 50 );
wp_update_post(
array(
'ID' => $post->ID,
'post_name' => $slug,
)
);
remove_filter( 'wp_unique_post_slug', 'wpse_140132_attachment_slug_as_file_name_uppercase', 50 );
}
}
}
}
add_action( 'add_attachment', 'wpse_140132_attachment_slug_as_file_name' );
/**
* @see wpse_140132_attachment_slug_as_file_name()
*
* @param string $slug
* @return string
*/
function wpse_140132_attachment_slug_as_file_name_uppercase( $slug ) {
return strtoupper( $slug );
}