-
-
Save chrisdavidmiles/770ffbfe428b440fd007bcb6b08e94d7 to your computer and use it in GitHub Desktop.
WordPress Plugin: Auto Rename Uploads to Match Post Slug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Auto Rename Uploads to Match Post Slug | |
* Plugin URI: https://gist.github.com/chrisdavidmiles/770ffbfe428b440fd007bcb6b08e94d7 | |
* Description: Uploads will be automatically renamed to match the post slug | |
* Author: Chris David Miles | |
* Version: 0.1 | |
*/ | |
function auto_rename_uploads_to_post_slug( $filename ) { | |
$info = pathinfo( $filename ); | |
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension']; | |
$name = basename( $filename, $ext ); | |
if ( isset( $_REQUEST['post_id'] ) && is_numeric( $_REQUEST['post_id'] ) ) { | |
$postObj = get_post( $_REQUEST['post_id'] ); | |
$postSlug = sanitize_title( $postObj->post_title ); | |
} | |
if ( isset( $postSlug ) && ! empty( $postSlug ) && $postSlug != 'auto-draft' ) { | |
$finalFileName = $postSlug; | |
} // File name will be the same as the post slug. | |
else { | |
$finalFileName = sanitize_title( $name ); | |
} // File name will be the same as the image file name, but sanitized. | |
return $finalFileName . $ext; | |
} | |
add_filter( 'sanitize_file_name', 'auto_rename_uploads_to_post_slug', 100 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment