你可以钩住add_attachment
并强制slug按如下方式处理文件名:
Update: 要使slug大写,需要在wp_unique_post_slug
. 你不能简单地使用strtoupper( $slug )
WordPress在更新函数中清理(小写)。
/**
* 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 );
}