diff --git a/features/media-import.feature b/features/media-import.feature index 1c9e4045..e50aa53a 100644 --- a/features/media-import.feature +++ b/features/media-import.feature @@ -25,6 +25,17 @@ Feature: Manage WordPress attachments Success: Imported 1 of 1 items. """ + Scenario: Import media from remote URL and use input file as attachment name + When I run `wp media import 'http://wp-cli.org/behat-data/codeispoetry.png' --file_name=abc` + Then STDOUT should contain: + """ + file name abc.png + """ + And STDOUT should contain: + """ + Success: Imported 1 of 1 items. + """ + Scenario: Fail to import missing image When I try `wp media import gobbledygook.png` Then STDERR should be: diff --git a/src/Media_Command.php b/src/Media_Command.php index 96945760..7993b172 100644 --- a/src/Media_Command.php +++ b/src/Media_Command.php @@ -185,6 +185,9 @@ public function regenerate( $args, $assoc_args = array() ) { * [--post_name=] * : Name of the post to attach the imported files to. * + * [--file_name=] + * : Attachment name (post_name field). + * * [--title=] * : Attachment title (post title field). * @@ -249,6 +252,7 @@ public function import( $args, $assoc_args = array() ) { $assoc_args = wp_parse_args( $assoc_args, array( + 'file_name' => '', 'title' => '', 'caption' => '', 'alt' => '', @@ -328,6 +332,11 @@ public function import( $args, $assoc_args = array() ) { $name = strtok( Utils\basename( $file ), '?' ); } + if ( ! empty( $assoc_args['file_name'] ) ) { + $image_name = $this->get_image_name( $name, $assoc_args['file_name'] ); + $name = ! empty( $image_name ) ? $image_name : $name; + } + $file_array = array( 'tmp_name' => $tempfile, 'name' => $name, @@ -414,6 +423,10 @@ public function import( $args, $assoc_args = array() ) { } $attachment_success_text = ''; + if ( $assoc_args['file_name'] ) { + $attachment_success_text .= " with file name {$name}"; + } + if ( $assoc_args['post_id'] ) { $attachment_success_text = " and attached to post {$assoc_args['post_id']}"; if ( Utils\get_flag_value( $assoc_args, 'featured_image' ) ) { @@ -1259,4 +1272,20 @@ private function get_real_attachment_url( $attachment_id ) { return wp_get_attachment_url( $attachment_id ); } + + /** + * Create image slug based on user input slug. + * Add basename extension to slug. + * + * @param string $basename Default slu of image. + * @param string $slug User input slug. + * + * @return string Image slug with extension. + */ + private function get_image_name( $basename, $slug ) { + + $extension = pathinfo( $basename, PATHINFO_EXTENSION ); + + return $slug . '.' . $extension; + } }