3 * WordPress Administration Media API.
6 * @subpackage Administration
10 * Defines the default media upload tabs
14 * @return array default tabs
16 function media_upload_tabs() {
17 $_default_tabs = array(
18 'type' => __('From Computer'), // handler action suffix => tab text
19 'type_url' => __('From URL'),
20 'gallery' => __('Gallery'),
21 'library' => __('Media Library')
25 * Filters the available tabs in the legacy (pre-3.5.0) media popup.
29 * @param array $_default_tabs An array of media tabs.
31 return apply_filters( 'media_upload_tabs', $_default_tabs );
35 * Adds the gallery tab back to the tabs array if post has image attachments
39 * @global wpdb $wpdb WordPress database abstraction object.
42 * @return array $tabs with gallery if post has image attachment
44 function update_gallery_tab($tabs) {
47 if ( !isset($_REQUEST['post_id']) ) {
48 unset($tabs['gallery']);
52 $post_id = intval($_REQUEST['post_id']);
55 $attachments = intval( $wpdb->get_var( $wpdb->prepare( "SELECT count(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent = %d", $post_id ) ) );
57 if ( empty($attachments) ) {
58 unset($tabs['gallery']);
62 $tabs['gallery'] = sprintf(__('Gallery (%s)'), "<span id='attachments-count'>$attachments</span>");
68 * Outputs the legacy media upload tabs UI.
72 * @global string $redir_tab
74 function the_media_upload_tabs() {
76 $tabs = media_upload_tabs();
79 if ( !empty($tabs) ) {
80 echo "<ul id='sidemenu'>\n";
81 if ( isset($redir_tab) && array_key_exists($redir_tab, $tabs) ) {
82 $current = $redir_tab;
83 } elseif ( isset($_GET['tab']) && array_key_exists($_GET['tab'], $tabs) ) {
84 $current = $_GET['tab'];
86 /** This filter is documented in wp-admin/media-upload.php */
87 $current = apply_filters( 'media_upload_default_tab', $default );
90 foreach ( $tabs as $callback => $text ) {
93 if ( $current == $callback )
94 $class = " class='current'";
96 $href = add_query_arg(array('tab' => $callback, 's' => false, 'paged' => false, 'post_mime_type' => false, 'm' => false));
97 $link = "<a href='" . esc_url($href) . "'$class>$text</a>";
98 echo "\t<li id='" . esc_attr("tab-$callback") . "'>$link</li>\n";
105 * Retrieves the image HTML to send to the editor.
109 * @param int $id Image attachment id.
110 * @param string $caption Image caption.
111 * @param string $title Image title attribute.
112 * @param string $align Image CSS alignment property.
113 * @param string $url Optional. Image src URL. Default empty.
114 * @param bool|string $rel Optional. Value for rel attribute or whether to add a default value. Default false.
115 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
116 * and height values in pixels (in that order). Default 'medium'.
117 * @param string $alt Optional. Image alt attribute. Default empty.
118 * @return string The HTML output to insert into the editor.
120 function get_image_send_to_editor( $id, $caption, $title, $align, $url = '', $rel = false, $size = 'medium', $alt = '' ) {
122 $html = get_image_tag( $id, $alt, '', $align, $size );
125 if ( is_string( $rel ) ) {
126 $rel = ' rel="' . esc_attr( $rel ) . '"';
128 $rel = ' rel="attachment wp-att-' . intval( $id ) . '"';
135 $html = '<a href="' . esc_attr( $url ) . '"' . $rel . '>' . $html . '</a>';
138 * Filters the image HTML markup to send to the editor when inserting an image.
142 * @param string $html The image HTML markup to send.
143 * @param int $id The attachment id.
144 * @param string $caption The image caption.
145 * @param string $title The image title.
146 * @param string $align The image alignment.
147 * @param string $url The image source URL.
148 * @param string|array $size Size of image. Image size or array of width and height values
149 * (in that order). Default 'medium'.
150 * @param string $alt The image alternative, or alt, text.
152 $html = apply_filters( 'image_send_to_editor', $html, $id, $caption, $title, $align, $url, $size, $alt );
158 * Adds image shortcode with caption to editor
162 * @param string $html
164 * @param string $caption image caption
165 * @param string $title image title attribute
166 * @param string $align image css alignment property
167 * @param string $url image src url
168 * @param string $size image size (thumbnail, medium, large, full or added with add_image_size() )
169 * @param string $alt image alt attribute
172 function image_add_caption( $html, $id, $caption, $title, $align, $url, $size, $alt = '' ) {
175 * Filters the caption text.
177 * Note: If the caption text is empty, the caption shortcode will not be appended
178 * to the image HTML when inserted into the editor.
180 * Passing an empty value also prevents the {@see 'image_add_caption_shortcode'}
181 * Filters from being evaluated at the end of image_add_caption().
185 * @param string $caption The original caption text.
186 * @param int $id The attachment ID.
188 $caption = apply_filters( 'image_add_caption_text', $caption, $id );
191 * Filters whether to disable captions.
193 * Prevents image captions from being appended to image HTML when inserted into the editor.
197 * @param bool $bool Whether to disable appending captions. Returning true to the filter
198 * will disable captions. Default empty string.
200 if ( empty($caption) || apply_filters( 'disable_captions', '' ) )
203 $id = ( 0 < (int) $id ) ? 'attachment_' . $id : '';
205 if ( ! preg_match( '/width=["\']([0-9]+)/', $html, $matches ) )
208 $width = $matches[1];
210 $caption = str_replace( array("\r\n", "\r"), "\n", $caption);
211 $caption = preg_replace_callback( '/<[a-zA-Z0-9]+(?: [^<>]+>)*/', '_cleanup_image_add_caption', $caption );
213 // Convert any remaining line breaks to <br>.
214 $caption = preg_replace( '/[ \n\t]*\n[ \t]*/', '<br />', $caption );
216 $html = preg_replace( '/(class=["\'][^\'"]*)align(none|left|right|center)\s?/', '$1', $html );
220 $shcode = '[caption id="' . $id . '" align="align' . $align . '" width="' . $width . '"]' . $html . ' ' . $caption . '[/caption]';
223 * Filters the image HTML markup including the caption shortcode.
227 * @param string $shcode The image HTML markup with caption shortcode.
228 * @param string $html The image HTML markup.
230 return apply_filters( 'image_add_caption_shortcode', $shcode, $html );
234 * Private preg_replace callback used in image_add_caption()
239 function _cleanup_image_add_caption( $matches ) {
240 // Remove any line breaks from inside the tags.
241 return preg_replace( '/[\r\n\t]+/', ' ', $matches[0] );
245 * Adds image html to editor
249 * @param string $html
251 function media_send_to_editor($html) {
253 <script type="text/javascript">
254 var win = window.dialogArguments || opener || parent || top;
255 win.send_to_editor( <?php echo wp_json_encode( $html ); ?> );
262 * Save a file submitted from a POST request and create an attachment post for it.
266 * @param string $file_id Index of the `$_FILES` array that the file was sent. Required.
267 * @param int $post_id The post ID of a post to attach the media item to. Required, but can
268 * be set to 0, creating a media item that has no relationship to a post.
269 * @param array $post_data Overwrite some of the attachment. Optional.
270 * @param array $overrides Override the wp_handle_upload() behavior. Optional.
271 * @return int|WP_Error ID of the attachment or a WP_Error object on failure.
273 function media_handle_upload($file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false )) {
275 $time = current_time('mysql');
276 if ( $post = get_post($post_id) ) {
277 if ( substr( $post->post_date, 0, 4 ) > 0 )
278 $time = $post->post_date;
281 $file = wp_handle_upload($_FILES[$file_id], $overrides, $time);
283 if ( isset($file['error']) )
284 return new WP_Error( 'upload_error', $file['error'] );
286 $name = $_FILES[$file_id]['name'];
287 $ext = pathinfo( $name, PATHINFO_EXTENSION );
288 $name = wp_basename( $name, ".$ext" );
291 $type = $file['type'];
292 $file = $file['file'];
293 $title = sanitize_text_field( $name );
297 if ( preg_match( '#^audio#', $type ) ) {
298 $meta = wp_read_audio_metadata( $file );
300 if ( ! empty( $meta['title'] ) ) {
301 $title = $meta['title'];
304 if ( ! empty( $title ) ) {
306 if ( ! empty( $meta['album'] ) && ! empty( $meta['artist'] ) ) {
307 /* translators: 1: audio track title, 2: album title, 3: artist name */
308 $content .= sprintf( __( '"%1$s" from %2$s by %3$s.' ), $title, $meta['album'], $meta['artist'] );
309 } elseif ( ! empty( $meta['album'] ) ) {
310 /* translators: 1: audio track title, 2: album title */
311 $content .= sprintf( __( '"%1$s" from %2$s.' ), $title, $meta['album'] );
312 } elseif ( ! empty( $meta['artist'] ) ) {
313 /* translators: 1: audio track title, 2: artist name */
314 $content .= sprintf( __( '"%1$s" by %2$s.' ), $title, $meta['artist'] );
316 /* translators: 1: audio track title */
317 $content .= sprintf( __( '"%s".' ), $title );
320 } elseif ( ! empty( $meta['album'] ) ) {
322 if ( ! empty( $meta['artist'] ) ) {
323 /* translators: 1: audio album title, 2: artist name */
324 $content .= sprintf( __( '%1$s by %2$s.' ), $meta['album'], $meta['artist'] );
326 $content .= $meta['album'] . '.';
329 } elseif ( ! empty( $meta['artist'] ) ) {
331 $content .= $meta['artist'] . '.';
335 if ( ! empty( $meta['year'] ) ) {
336 /* translators: Audio file track information. 1: Year of audio track release */
337 $content .= ' ' . sprintf( __( 'Released: %d.' ), $meta['year'] );
340 if ( ! empty( $meta['track_number'] ) ) {
341 $track_number = explode( '/', $meta['track_number'] );
342 if ( isset( $track_number[1] ) ) {
343 /* translators: Audio file track information. 1: Audio track number, 2: Total audio tracks */
344 $content .= ' ' . sprintf( __( 'Track %1$s of %2$s.' ), number_format_i18n( $track_number[0] ), number_format_i18n( $track_number[1] ) );
346 /* translators: Audio file track information. 1: Audio track number */
347 $content .= ' ' . sprintf( __( 'Track %1$s.' ), number_format_i18n( $track_number[0] ) );
351 if ( ! empty( $meta['genre'] ) ) {
352 /* translators: Audio file genre information. 1: Audio genre name */
353 $content .= ' ' . sprintf( __( 'Genre: %s.' ), $meta['genre'] );
356 // Use image exif/iptc data for title and caption defaults if possible.
357 } elseif ( 0 === strpos( $type, 'image/' ) && $image_meta = @wp_read_image_metadata( $file ) ) {
358 if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
359 $title = $image_meta['title'];
362 if ( trim( $image_meta['caption'] ) ) {
363 $excerpt = $image_meta['caption'];
367 // Construct the attachment array
368 $attachment = array_merge( array(
369 'post_mime_type' => $type,
371 'post_parent' => $post_id,
372 'post_title' => $title,
373 'post_content' => $content,
374 'post_excerpt' => $excerpt,
377 // This should never be set as it would then overwrite an existing attachment.
378 unset( $attachment['ID'] );
381 $id = wp_insert_attachment($attachment, $file, $post_id);
382 if ( !is_wp_error($id) ) {
383 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
391 * Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload().
395 * @param array $file_array Array similar to a `$_FILES` upload array.
396 * @param int $post_id The post ID the media is associated with.
397 * @param string $desc Optional. Description of the side-loaded file. Default null.
398 * @param array $post_data Optional. Post data to override. Default empty array.
399 * @return int|object The ID of the attachment or a WP_Error on failure.
401 function media_handle_sideload( $file_array, $post_id, $desc = null, $post_data = array() ) {
402 $overrides = array('test_form'=>false);
404 $time = current_time( 'mysql' );
405 if ( $post = get_post( $post_id ) ) {
406 if ( substr( $post->post_date, 0, 4 ) > 0 )
407 $time = $post->post_date;
410 $file = wp_handle_sideload( $file_array, $overrides, $time );
411 if ( isset($file['error']) )
412 return new WP_Error( 'upload_error', $file['error'] );
415 $type = $file['type'];
416 $file = $file['file'];
417 $title = preg_replace('/\.[^.]+$/', '', basename($file));
420 // Use image exif/iptc data for title and caption defaults if possible.
421 if ( $image_meta = @wp_read_image_metadata($file) ) {
422 if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) )
423 $title = $image_meta['title'];
424 if ( trim( $image_meta['caption'] ) )
425 $content = $image_meta['caption'];
428 if ( isset( $desc ) )
431 // Construct the attachment array.
432 $attachment = array_merge( array(
433 'post_mime_type' => $type,
435 'post_parent' => $post_id,
436 'post_title' => $title,
437 'post_content' => $content,
440 // This should never be set as it would then overwrite an existing attachment.
441 unset( $attachment['ID'] );
443 // Save the attachment metadata
444 $id = wp_insert_attachment($attachment, $file, $post_id);
445 if ( !is_wp_error($id) )
446 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
452 * Adds the iframe to display content for the media upload page
456 * @global int $body_id
458 * @param string|callable $content_func
460 function wp_iframe($content_func /* ... */) {
461 _wp_admin_html_begin();
463 <title><?php bloginfo('name') ?> › <?php _e('Uploads'); ?> — <?php _e('WordPress'); ?></title>
466 wp_enqueue_style( 'colors' );
467 // Check callback name for 'media'
468 if ( ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) )
469 || ( ! is_array( $content_func ) && 0 === strpos( $content_func, 'media' ) ) )
470 wp_enqueue_style( 'deprecated-media' );
471 wp_enqueue_style( 'ie' );
473 <script type="text/javascript">
474 addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
475 var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>', pagenow = 'media-upload-popup', adminpage = 'media-upload-popup',
476 isRtl = <?php echo (int) is_rtl(); ?>;
479 /** This action is documented in wp-admin/admin-header.php */
480 do_action( 'admin_enqueue_scripts', 'media-upload-popup' );
483 * Fires when admin styles enqueued for the legacy (pre-3.5.0) media upload popup are printed.
487 do_action( 'admin_print_styles-media-upload-popup' );
489 /** This action is documented in wp-admin/admin-header.php */
490 do_action( 'admin_print_styles' );
493 * Fires when admin scripts enqueued for the legacy (pre-3.5.0) media upload popup are printed.
497 do_action( 'admin_print_scripts-media-upload-popup' );
499 /** This action is documented in wp-admin/admin-header.php */
500 do_action( 'admin_print_scripts' );
503 * Fires when scripts enqueued for the admin header for the legacy (pre-3.5.0)
504 * media upload popup are printed.
508 do_action( 'admin_head-media-upload-popup' );
510 /** This action is documented in wp-admin/admin-header.php */
511 do_action( 'admin_head' );
513 if ( is_string( $content_func ) ) {
515 * Fires in the admin header for each specific form tab in the legacy
516 * (pre-3.5.0) media upload popup.
518 * The dynamic portion of the hook, `$content_func`, refers to the form
519 * callback for the media upload type. Possible values include
520 * 'media_upload_type_form', 'media_upload_type_url_form', and
521 * 'media_upload_library_form'.
525 do_action( "admin_head_{$content_func}" );
529 <body<?php if ( isset($GLOBALS['body_id']) ) echo ' id="' . $GLOBALS['body_id'] . '"'; ?> class="wp-core-ui no-js">
530 <script type="text/javascript">
531 document.body.className = document.body.className.replace('no-js', 'js');
534 $args = func_get_args();
535 $args = array_slice($args, 1);
536 call_user_func_array($content_func, $args);
538 /** This action is documented in wp-admin/admin-footer.php */
539 do_action( 'admin_print_footer_scripts' );
541 <script type="text/javascript">if(typeof wpOnload=='function')wpOnload();</script>
548 * Adds the media button to the editor
552 * @global int $post_ID
554 * @staticvar int $instance
556 * @param string $editor_id
558 function media_buttons($editor_id = 'content') {
559 static $instance = 0;
563 if ( ! $post && ! empty( $GLOBALS['post_ID'] ) )
564 $post = $GLOBALS['post_ID'];
566 wp_enqueue_media( array(
570 $img = '<span class="wp-media-buttons-icon"></span> ';
572 $id_attribute = $instance === 1 ? ' id="insert-media-button"' : '';
573 printf( '<button type="button"%s class="button insert-media add_media" data-editor="%s">%s</button>',
575 esc_attr( $editor_id ),
576 $img . __( 'Add Media' )
579 * Filters the legacy (pre-3.5.0) media buttons.
581 * Use {@see 'media_buttons'} action instead.
584 * @deprecated 3.5.0 Use {@see 'media_buttons'} action instead.
586 * @param string $string Media buttons context. Default empty.
588 $legacy_filter = apply_filters( 'media_buttons_context', '' );
590 if ( $legacy_filter ) {
591 // #WP22559. Close <a> if a plugin started by closing <a> to open their own <a> tag.
592 if ( 0 === stripos( trim( $legacy_filter ), '</a>' ) )
593 $legacy_filter .= '</a>';
600 * @global int $post_ID
601 * @param string $type
602 * @param int $post_id
606 function get_upload_iframe_src( $type = null, $post_id = null, $tab = null ) {
609 if ( empty( $post_id ) )
612 $upload_iframe_src = add_query_arg( 'post_id', (int) $post_id, admin_url('media-upload.php') );
614 if ( $type && 'media' != $type )
615 $upload_iframe_src = add_query_arg('type', $type, $upload_iframe_src);
617 if ( ! empty( $tab ) )
618 $upload_iframe_src = add_query_arg('tab', $tab, $upload_iframe_src);
621 * Filters the upload iframe source URL for a specific media type.
623 * The dynamic portion of the hook name, `$type`, refers to the type
628 * @param string $upload_iframe_src The upload iframe source URL by type.
630 $upload_iframe_src = apply_filters( "{$type}_upload_iframe_src", $upload_iframe_src );
632 return add_query_arg('TB_iframe', true, $upload_iframe_src);
636 * Handles form submissions for the legacy media uploader.
640 * @return mixed void|object WP_Error on failure
642 function media_upload_form_handler() {
643 check_admin_referer('media-form');
647 if ( isset($_POST['send']) ) {
648 $keys = array_keys( $_POST['send'] );
649 $send_id = (int) reset( $keys );
652 if ( !empty($_POST['attachments']) ) foreach ( $_POST['attachments'] as $attachment_id => $attachment ) {
653 $post = $_post = get_post($attachment_id, ARRAY_A);
655 if ( !current_user_can( 'edit_post', $attachment_id ) )
658 if ( isset($attachment['post_content']) )
659 $post['post_content'] = $attachment['post_content'];
660 if ( isset($attachment['post_title']) )
661 $post['post_title'] = $attachment['post_title'];
662 if ( isset($attachment['post_excerpt']) )
663 $post['post_excerpt'] = $attachment['post_excerpt'];
664 if ( isset($attachment['menu_order']) )
665 $post['menu_order'] = $attachment['menu_order'];
667 if ( isset($send_id) && $attachment_id == $send_id ) {
668 if ( isset($attachment['post_parent']) )
669 $post['post_parent'] = $attachment['post_parent'];
673 * Filters the attachment fields to be saved.
677 * @see wp_get_attachment_metadata()
679 * @param array $post An array of post data.
680 * @param array $attachment An array of attachment metadata.
682 $post = apply_filters( 'attachment_fields_to_save', $post, $attachment );
684 if ( isset($attachment['image_alt']) ) {
685 $image_alt = wp_unslash( $attachment['image_alt'] );
686 if ( $image_alt != get_post_meta($attachment_id, '_wp_attachment_image_alt', true) ) {
687 $image_alt = wp_strip_all_tags( $image_alt, true );
689 // Update_meta expects slashed.
690 update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
694 if ( isset($post['errors']) ) {
695 $errors[$attachment_id] = $post['errors'];
696 unset($post['errors']);
699 if ( $post != $_post )
700 wp_update_post($post);
702 foreach ( get_attachment_taxonomies($post) as $t ) {
703 if ( isset($attachment[$t]) )
704 wp_set_object_terms($attachment_id, array_map('trim', preg_split('/,+/', $attachment[$t])), $t, false);
708 if ( isset($_POST['insert-gallery']) || isset($_POST['update-gallery']) ) { ?>
709 <script type="text/javascript">
710 var win = window.dialogArguments || opener || parent || top;
717 if ( isset($send_id) ) {
718 $attachment = wp_unslash( $_POST['attachments'][$send_id] );
720 $html = isset( $attachment['post_title'] ) ? $attachment['post_title'] : '';
721 if ( !empty($attachment['url']) ) {
723 if ( strpos($attachment['url'], 'attachment_id') || get_attachment_link($send_id) == $attachment['url'] )
724 $rel = " rel='attachment wp-att-" . esc_attr($send_id) . "'";
725 $html = "<a href='{$attachment['url']}'$rel>$html</a>";
729 * Filters the HTML markup for a media item sent to the editor.
733 * @see wp_get_attachment_metadata()
735 * @param string $html HTML markup for a media item sent to the editor.
736 * @param int $send_id The first key from the $_POST['send'] data.
737 * @param array $attachment Array of attachment metadata.
739 $html = apply_filters( 'media_send_to_editor', $html, $send_id, $attachment );
740 return media_send_to_editor($html);
747 * Handles the process of uploading media.
751 * @return null|string
753 function wp_media_upload_handler() {
757 if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
758 check_admin_referer('media-form');
759 // Upload File button was clicked
760 $id = media_handle_upload('async-upload', $_REQUEST['post_id']);
762 if ( is_wp_error($id) ) {
763 $errors['upload_error'] = $id;
768 if ( !empty($_POST['insertonlybutton']) ) {
769 $src = $_POST['src'];
770 if ( !empty($src) && !strpos($src, '://') )
771 $src = "http://$src";
773 if ( isset( $_POST['media_type'] ) && 'image' != $_POST['media_type'] ) {
774 $title = esc_html( wp_unslash( $_POST['title'] ) );
775 if ( empty( $title ) )
776 $title = esc_html( basename( $src ) );
778 if ( $title && $src )
779 $html = "<a href='" . esc_url($src) . "'>$title</a>";
782 if ( ( $ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src ) ) && ( $ext_type = wp_ext2type( $ext ) )
783 && ( 'audio' == $ext_type || 'video' == $ext_type ) )
787 * Filters the URL sent to the editor for a specific media type.
789 * The dynamic portion of the hook name, `$type`, refers to the type
790 * of media being sent.
794 * @param string $html HTML markup sent to the editor.
795 * @param string $src Media source URL.
796 * @param string $title Media title.
798 $html = apply_filters( "{$type}_send_to_editor_url", $html, esc_url_raw( $src ), $title );
801 $alt = esc_attr( wp_unslash( $_POST['alt'] ) );
802 if ( isset($_POST['align']) ) {
803 $align = esc_attr( wp_unslash( $_POST['align'] ) );
804 $class = " class='align$align'";
807 $html = "<img src='" . esc_url($src) . "' alt='$alt'$class />";
810 * Filters the image URL sent to the editor.
814 * @param string $html HTML markup sent to the editor for an image.
815 * @param string $src Image source URL.
816 * @param string $alt Image alternate, or alt, text.
817 * @param string $align The image alignment. Default 'alignnone'. Possible values include
818 * 'alignleft', 'aligncenter', 'alignright', 'alignnone'.
820 $html = apply_filters( 'image_send_to_editor_url', $html, esc_url_raw( $src ), $alt, $align );
823 return media_send_to_editor($html);
826 if ( isset( $_POST['save'] ) ) {
827 $errors['upload_notice'] = __('Saved.');
828 wp_enqueue_script( 'admin-gallery' );
829 return wp_iframe( 'media_upload_gallery_form', $errors );
831 } elseif ( ! empty( $_POST ) ) {
832 $return = media_upload_form_handler();
834 if ( is_string($return) )
836 if ( is_array($return) )
840 if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' ) {
842 if ( isset( $_GET['type'] ) && in_array( $_GET['type'], array( 'video', 'audio', 'file' ) ) )
843 $type = $_GET['type'];
844 return wp_iframe( 'media_upload_type_url_form', $type, $errors, $id );
847 return wp_iframe( 'media_upload_type_form', 'image', $errors, $id );
851 * Downloads an image from the specified URL and attaches it to a post.
854 * @since 4.2.0 Introduced the `$return` parameter.
856 * @param string $file The URL of the image to download.
857 * @param int $post_id The post ID the media is to be associated with.
858 * @param string $desc Optional. Description of the image.
859 * @param string $return Optional. Accepts 'html' (image tag html) or 'src' (URL). Default 'html'.
860 * @return string|WP_Error Populated HTML img tag on success, WP_Error object otherwise.
862 function media_sideload_image( $file, $post_id, $desc = null, $return = 'html' ) {
863 if ( ! empty( $file ) ) {
865 // Set variables for storage, fix file filename for query strings.
866 preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
868 return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) );
871 $file_array = array();
872 $file_array['name'] = basename( $matches[0] );
874 // Download file to temp location.
875 $file_array['tmp_name'] = download_url( $file );
877 // If error storing temporarily, return the error.
878 if ( is_wp_error( $file_array['tmp_name'] ) ) {
879 return $file_array['tmp_name'];
882 // Do the validation and storage stuff.
883 $id = media_handle_sideload( $file_array, $post_id, $desc );
885 // If error storing permanently, unlink.
886 if ( is_wp_error( $id ) ) {
887 @unlink( $file_array['tmp_name'] );
891 $src = wp_get_attachment_url( $id );
894 // Finally, check to make sure the file has been saved, then return the HTML.
895 if ( ! empty( $src ) ) {
896 if ( $return === 'src' ) {
900 $alt = isset( $desc ) ? esc_attr( $desc ) : '';
901 $html = "<img src='$src' alt='$alt' />";
904 return new WP_Error( 'image_sideload_failed' );
909 * Retrieves the legacy media uploader form in an iframe.
913 * @return string|null
915 function media_upload_gallery() {
918 if ( !empty($_POST) ) {
919 $return = media_upload_form_handler();
921 if ( is_string($return) )
923 if ( is_array($return) )
927 wp_enqueue_script('admin-gallery');
928 return wp_iframe( 'media_upload_gallery_form', $errors );
932 * Retrieves the legacy media library form in an iframe.
936 * @return string|null
938 function media_upload_library() {
940 if ( !empty($_POST) ) {
941 $return = media_upload_form_handler();
943 if ( is_string($return) )
945 if ( is_array($return) )
949 return wp_iframe( 'media_upload_library_form', $errors );
953 * Retrieve HTML for the image alignment radio buttons with the specified one checked.
957 * @param WP_Post $post
958 * @param string $checked
961 function image_align_input_fields( $post, $checked = '' ) {
963 if ( empty($checked) )
964 $checked = get_user_setting('align', 'none');
966 $alignments = array('none' => __('None'), 'left' => __('Left'), 'center' => __('Center'), 'right' => __('Right'));
967 if ( !array_key_exists( (string) $checked, $alignments ) )
971 foreach ( $alignments as $name => $label ) {
972 $name = esc_attr($name);
973 $out[] = "<input type='radio' name='attachments[{$post->ID}][align]' id='image-align-{$name}-{$post->ID}' value='$name'".
974 ( $checked == $name ? " checked='checked'" : "" ) .
975 " /><label for='image-align-{$name}-{$post->ID}' class='align image-align-{$name}-label'>$label</label>";
977 return join("\n", $out);
981 * Retrieve HTML for the size radio buttons with the specified one checked.
985 * @param WP_Post $post
986 * @param bool|string $check
989 function image_size_input_fields( $post, $check = '' ) {
991 * Filters the names and labels of the default image sizes.
995 * @param array $size_names Array of image sizes and their names. Default values
996 * include 'Thumbnail', 'Medium', 'Large', 'Full Size'.
998 $size_names = apply_filters( 'image_size_names_choose', array(
999 'thumbnail' => __( 'Thumbnail' ),
1000 'medium' => __( 'Medium' ),
1001 'large' => __( 'Large' ),
1002 'full' => __( 'Full Size' )
1005 if ( empty( $check ) ) {
1006 $check = get_user_setting('imgsize', 'medium');
1010 foreach ( $size_names as $size => $label ) {
1011 $downsize = image_downsize( $post->ID, $size );
1014 // Is this size selectable?
1015 $enabled = ( $downsize[3] || 'full' == $size );
1016 $css_id = "image-size-{$size}-{$post->ID}";
1018 // If this size is the default but that's not available, don't select it.
1019 if ( $size == $check ) {
1021 $checked = " checked='checked'";
1025 } elseif ( ! $check && $enabled && 'thumbnail' != $size ) {
1027 * If $check is not enabled, default to the first available size
1028 * that's bigger than a thumbnail.
1031 $checked = " checked='checked'";
1034 $html = "<div class='image-size-item'><input type='radio' " . disabled( $enabled, false, false ) . "name='attachments[$post->ID][image-size]' id='{$css_id}' value='{$size}'$checked />";
1036 $html .= "<label for='{$css_id}'>$label</label>";
1038 // Only show the dimensions if that choice is available.
1040 $html .= " <label for='{$css_id}' class='help'>" . sprintf( "(%d × %d)", $downsize[1], $downsize[2] ). "</label>";
1048 'label' => __( 'Size' ),
1050 'html' => join( "\n", $out ),
1055 * Retrieve HTML for the Link URL buttons with the default link type as specified.
1059 * @param WP_Post $post
1060 * @param string $url_type
1063 function image_link_input_fields($post, $url_type = '') {
1065 $file = wp_get_attachment_url($post->ID);
1066 $link = get_attachment_link($post->ID);
1068 if ( empty($url_type) )
1069 $url_type = get_user_setting('urlbutton', 'post');
1072 if ( $url_type == 'file' )
1074 elseif ( $url_type == 'post' )
1078 <input type='text' class='text urlfield' name='attachments[$post->ID][url]' value='" . esc_attr($url) . "' /><br />
1079 <button type='button' class='button urlnone' data-link-url=''>" . __('None') . "</button>
1080 <button type='button' class='button urlfile' data-link-url='" . esc_attr($file) . "'>" . __('File URL') . "</button>
1081 <button type='button' class='button urlpost' data-link-url='" . esc_attr($link) . "'>" . __('Attachment Post URL') . "</button>
1086 * Output a textarea element for inputting an attachment caption.
1090 * @param WP_Post $edit_post Attachment WP_Post object.
1091 * @return string HTML markup for the textarea element.
1093 function wp_caption_input_textarea($edit_post) {
1094 // Post data is already escaped.
1095 $name = "attachments[{$edit_post->ID}][post_excerpt]";
1097 return '<textarea name="' . $name . '" id="' . $name . '">' . $edit_post->post_excerpt . '</textarea>';
1101 * Retrieves the image attachment fields to edit form fields.
1105 * @param array $form_fields
1106 * @param object $post
1109 function image_attachment_fields_to_edit($form_fields, $post) {
1110 return $form_fields;
1114 * Retrieves the single non-image attachment fields to edit form fields.
1118 * @param array $form_fields An array of attachment form fields.
1119 * @param WP_Post $post The WP_Post attachment object.
1120 * @return array Filtered attachment form fields.
1122 function media_single_attachment_fields_to_edit( $form_fields, $post ) {
1123 unset($form_fields['url'], $form_fields['align'], $form_fields['image-size']);
1124 return $form_fields;
1128 * Retrieves the post non-image attachment fields to edito form fields.
1132 * @param array $form_fields An array of attachment form fields.
1133 * @param WP_Post $post The WP_Post attachment object.
1134 * @return array Filtered attachment form fields.
1136 function media_post_single_attachment_fields_to_edit( $form_fields, $post ) {
1137 unset($form_fields['image_url']);
1138 return $form_fields;
1142 * Filters input from media_upload_form_handler() and assigns a default
1143 * post_title from the file name if none supplied.
1145 * Illustrates the use of the {@see 'attachment_fields_to_save'} filter
1146 * which can be used to add default values to any field before saving to DB.
1150 * @param array $post The WP_Post attachment object converted to an array.
1151 * @param array $attachment An array of attachment metadata.
1152 * @return array Filtered attachment post object.
1154 function image_attachment_fields_to_save( $post, $attachment ) {
1155 if ( substr( $post['post_mime_type'], 0, 5 ) == 'image' ) {
1156 if ( strlen( trim( $post['post_title'] ) ) == 0 ) {
1157 $attachment_url = ( isset( $post['attachment_url'] ) ) ? $post['attachment_url'] : $post['guid'];
1158 $post['post_title'] = preg_replace( '/\.\w+$/', '', wp_basename( $attachment_url ) );
1159 $post['errors']['post_title']['errors'][] = __( 'Empty Title filled from filename.' );
1167 * Retrieves the media element HTML to send to the editor.
1171 * @param string $html
1172 * @param integer $attachment_id
1173 * @param array $attachment
1176 function image_media_send_to_editor($html, $attachment_id, $attachment) {
1177 $post = get_post($attachment_id);
1178 if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
1179 $url = $attachment['url'];
1180 $align = !empty($attachment['align']) ? $attachment['align'] : 'none';
1181 $size = !empty($attachment['image-size']) ? $attachment['image-size'] : 'medium';
1182 $alt = !empty($attachment['image_alt']) ? $attachment['image_alt'] : '';
1183 $rel = ( strpos( $url, 'attachment_id') || $url === get_attachment_link( $attachment_id ) );
1185 return get_image_send_to_editor($attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size, $alt);
1192 * Retrieves the attachment fields to edit form fields.
1196 * @param WP_Post $post
1197 * @param array $errors
1200 function get_attachment_fields_to_edit($post, $errors = null) {
1201 if ( is_int($post) )
1202 $post = get_post($post);
1203 if ( is_array($post) )
1204 $post = new WP_Post( (object) $post );
1206 $image_url = wp_get_attachment_url($post->ID);
1208 $edit_post = sanitize_post($post, 'edit');
1210 $form_fields = array(
1211 'post_title' => array(
1212 'label' => __('Title'),
1213 'value' => $edit_post->post_title
1215 'image_alt' => array(),
1216 'post_excerpt' => array(
1217 'label' => __('Caption'),
1219 'html' => wp_caption_input_textarea($edit_post)
1221 'post_content' => array(
1222 'label' => __('Description'),
1223 'value' => $edit_post->post_content,
1224 'input' => 'textarea'
1227 'label' => __('Link URL'),
1229 'html' => image_link_input_fields($post, get_option('image_default_link_type')),
1230 'helps' => __('Enter a link URL or click above for presets.')
1232 'menu_order' => array(
1233 'label' => __('Order'),
1234 'value' => $edit_post->menu_order
1236 'image_url' => array(
1237 'label' => __('File URL'),
1239 'html' => "<input type='text' class='text urlfield' readonly='readonly' name='attachments[$post->ID][url]' value='" . esc_attr($image_url) . "' /><br />",
1240 'value' => wp_get_attachment_url($post->ID),
1241 'helps' => __('Location of the uploaded file.')
1245 foreach ( get_attachment_taxonomies($post) as $taxonomy ) {
1246 $t = (array) get_taxonomy($taxonomy);
1247 if ( ! $t['public'] || ! $t['show_ui'] )
1249 if ( empty($t['label']) )
1250 $t['label'] = $taxonomy;
1251 if ( empty($t['args']) )
1252 $t['args'] = array();
1254 $terms = get_object_term_cache($post->ID, $taxonomy);
1255 if ( false === $terms )
1256 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
1260 foreach ( $terms as $term )
1261 $values[] = $term->slug;
1262 $t['value'] = join(', ', $values);
1264 $form_fields[$taxonomy] = $t;
1267 // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
1268 // The recursive merge is easily traversed with array casting: foreach ( (array) $things as $thing )
1269 $form_fields = array_merge_recursive($form_fields, (array) $errors);
1271 // This was formerly in image_attachment_fields_to_edit().
1272 if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
1273 $alt = get_post_meta($post->ID, '_wp_attachment_image_alt', true);
1277 $form_fields['post_title']['required'] = true;
1279 $form_fields['image_alt'] = array(
1281 'label' => __('Alternative Text'),
1282 'helps' => __('Alt text for the image, e.g. “The Mona Lisa”')
1285 $form_fields['align'] = array(
1286 'label' => __('Alignment'),
1288 'html' => image_align_input_fields($post, get_option('image_default_align')),
1291 $form_fields['image-size'] = image_size_input_fields( $post, get_option('image_default_size', 'medium') );
1294 unset( $form_fields['image_alt'] );
1298 * Filters the attachment fields to edit.
1302 * @param array $form_fields An array of attachment form fields.
1303 * @param WP_Post $post The WP_Post attachment object.
1305 $form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
1307 return $form_fields;
1311 * Retrieve HTML for media items of post gallery.
1313 * The HTML markup retrieved will be created for the progress of SWF Upload
1314 * component. Will also create link for showing and hiding the form to modify
1315 * the image attachment.
1319 * @global WP_Query $wp_the_query
1321 * @param int $post_id Optional. Post ID.
1322 * @param array $errors Errors for attachment, if any.
1325 function get_media_items( $post_id, $errors ) {
1326 $attachments = array();
1328 $post = get_post($post_id);
1329 if ( $post && $post->post_type == 'attachment' )
1330 $attachments = array($post->ID => $post);
1332 $attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC') );
1334 if ( is_array($GLOBALS['wp_the_query']->posts) )
1335 foreach ( $GLOBALS['wp_the_query']->posts as $attachment )
1336 $attachments[$attachment->ID] = $attachment;
1340 foreach ( (array) $attachments as $id => $attachment ) {
1341 if ( $attachment->post_status == 'trash' )
1343 if ( $item = get_media_item( $id, array( 'errors' => isset($errors[$id]) ? $errors[$id] : null) ) )
1344 $output .= "\n<div id='media-item-$id' class='media-item child-of-$attachment->post_parent preloaded'><div class='progress hidden'><div class='bar'></div></div><div id='media-upload-error-$id' class='hidden'></div><div class='filename hidden'></div>$item\n</div>";
1351 * Retrieve HTML form for modifying the image attachment.
1355 * @global string $redir_tab
1357 * @param int $attachment_id Attachment ID for modification.
1358 * @param string|array $args Optional. Override defaults.
1359 * @return string HTML form for attachment.
1361 function get_media_item( $attachment_id, $args = null ) {
1364 if ( ( $attachment_id = intval( $attachment_id ) ) && $thumb_url = wp_get_attachment_image_src( $attachment_id, 'thumbnail', true ) )
1365 $thumb_url = $thumb_url[0];
1369 $post = get_post( $attachment_id );
1370 $current_post_id = !empty( $_GET['post_id'] ) ? (int) $_GET['post_id'] : 0;
1372 $default_args = array(
1374 'send' => $current_post_id ? post_type_supports( get_post_type( $current_post_id ), 'editor' ) : true,
1377 'show_title' => true
1379 $args = wp_parse_args( $args, $default_args );
1382 * Filters the arguments used to retrieve an image for the edit image form.
1386 * @see get_media_item
1388 * @param array $args An array of arguments.
1390 $r = apply_filters( 'get_media_item_args', $args );
1392 $toggle_on = __( 'Show' );
1393 $toggle_off = __( 'Hide' );
1395 $file = get_attached_file( $post->ID );
1396 $filename = esc_html( wp_basename( $file ) );
1397 $title = esc_attr( $post->post_title );
1399 $post_mime_types = get_post_mime_types();
1400 $keys = array_keys( wp_match_mime_types( array_keys( $post_mime_types ), $post->post_mime_type ) );
1401 $type = reset( $keys );
1402 $type_html = "<input type='hidden' id='type-of-$attachment_id' value='" . esc_attr( $type ) . "' />";
1404 $form_fields = get_attachment_fields_to_edit( $post, $r['errors'] );
1406 if ( $r['toggle'] ) {
1407 $class = empty( $r['errors'] ) ? 'startclosed' : 'startopen';
1409 <a class='toggle describe-toggle-on' href='#'>$toggle_on</a>
1410 <a class='toggle describe-toggle-off' href='#'>$toggle_off</a>";
1416 $display_title = ( !empty( $title ) ) ? $title : $filename; // $title shouldn't ever be empty, but just in case
1417 $display_title = $r['show_title'] ? "<div class='filename new'><span class='title'>" . wp_html_excerpt( $display_title, 60, '…' ) . "</span></div>" : '';
1419 $gallery = ( ( isset( $_REQUEST['tab'] ) && 'gallery' == $_REQUEST['tab'] ) || ( isset( $redir_tab ) && 'gallery' == $redir_tab ) );
1422 foreach ( $form_fields as $key => $val ) {
1423 if ( 'menu_order' == $key ) {
1425 $order = "<div class='menu_order'> <input class='menu_order_input' type='text' id='attachments[$attachment_id][menu_order]' name='attachments[$attachment_id][menu_order]' value='" . esc_attr( $val['value'] ). "' /></div>";
1427 $order = "<input type='hidden' name='attachments[$attachment_id][menu_order]' value='" . esc_attr( $val['value'] ) . "' />";
1429 unset( $form_fields['menu_order'] );
1435 $meta = wp_get_attachment_metadata( $post->ID );
1436 if ( isset( $meta['width'], $meta['height'] ) )
1437 $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']} × {$meta['height']}</span> ";
1440 * Filters the media metadata.
1444 * @param string $media_dims The HTML markup containing the media dimensions.
1445 * @param WP_Post $post The WP_Post attachment object.
1447 $media_dims = apply_filters( 'media_meta', $media_dims, $post );
1449 $image_edit_button = '';
1450 if ( wp_attachment_is_image( $post->ID ) && wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) {
1451 $nonce = wp_create_nonce( "image_editor-$post->ID" );
1452 $image_edit_button = "<input type='button' id='imgedit-open-btn-$post->ID' onclick='imageEdit.open( $post->ID, \"$nonce\" )' class='button' value='" . esc_attr__( 'Edit Image' ) . "' /> <span class='spinner'></span>";
1455 $attachment_url = get_permalink( $attachment_id );
1462 <table class='slidetoggle describe $class'>
1463 <thead class='media-item-info' id='media-head-$post->ID'>
1465 <td class='A1B1' id='thumbnail-head-$post->ID'>
1466 <p><a href='$attachment_url' target='_blank'><img class='thumbnail' src='$thumb_url' alt='' /></a></p>
1467 <p>$image_edit_button</p>
1470 <p><strong>" . __('File name:') . "</strong> $filename</p>
1471 <p><strong>" . __('File type:') . "</strong> $post->post_mime_type</p>
1472 <p><strong>" . __('Upload date:') . "</strong> " . mysql2date( __( 'F j, Y' ), $post->post_date ). '</p>';
1473 if ( !empty( $media_dims ) )
1474 $item .= "<p><strong>" . __('Dimensions:') . "</strong> $media_dims</p>\n";
1476 $item .= "</td></tr>\n";
1481 <tr><td colspan='2' class='imgedit-response' id='imgedit-response-$post->ID'></td></tr>\n
1482 <tr><td style='display:none' colspan='2' class='image-editor' id='image-editor-$post->ID'></td></tr>\n
1483 <tr><td colspan='2'><p class='media-types media-types-required-info'>" . sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) . "</p></td></tr>\n";
1487 'required' => false,
1489 'extra_rows' => array(),
1493 $r['send'] = get_submit_button( __( 'Insert into Post' ), '', "send[$attachment_id]", false );
1496 $delete = empty( $r['delete'] ) ? '' : $r['delete'];
1497 if ( $delete && current_user_can( 'delete_post', $attachment_id ) ) {
1498 if ( !EMPTY_TRASH_DAYS ) {
1499 $delete = "<a href='" . wp_nonce_url( "post.php?action=delete&post=$attachment_id", 'delete-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='delete-permanently'>" . __( 'Delete Permanently' ) . '</a>';
1500 } elseif ( !MEDIA_TRASH ) {
1501 $delete = "<a href='#' class='del-link' onclick=\"document.getElementById('del_attachment_$attachment_id').style.display='block';return false;\">" . __( 'Delete' ) . "</a>
1502 <div id='del_attachment_$attachment_id' class='del-attachment' style='display:none;'>" .
1503 /* translators: %s: file name */
1504 '<p>' . sprintf( __( 'You are about to delete %s.' ), '<strong>' . $filename . '</strong>' ) . "</p>
1505 <a href='" . wp_nonce_url( "post.php?action=delete&post=$attachment_id", 'delete-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='button'>" . __( 'Continue' ) . "</a>
1506 <a href='#' class='button' onclick=\"this.parentNode.style.display='none';return false;\">" . __( 'Cancel' ) . "</a>
1509 $delete = "<a href='" . wp_nonce_url( "post.php?action=trash&post=$attachment_id", 'trash-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='delete'>" . __( 'Move to Trash' ) . "</a>
1510 <a href='" . wp_nonce_url( "post.php?action=untrash&post=$attachment_id", 'untrash-post_' . $attachment_id ) . "' id='undo[$attachment_id]' class='undo hidden'>" . __( 'Undo' ) . "</a>";
1517 $calling_post_id = 0;
1518 if ( isset( $_GET['post_id'] ) ) {
1519 $calling_post_id = absint( $_GET['post_id'] );
1520 } elseif ( isset( $_POST ) && count( $_POST ) ) {// Like for async-upload where $_GET['post_id'] isn't set
1521 $calling_post_id = $post->post_parent;
1523 if ( 'image' == $type && $calling_post_id && current_theme_supports( 'post-thumbnails', get_post_type( $calling_post_id ) )
1524 && post_type_supports( get_post_type( $calling_post_id ), 'thumbnail' ) && get_post_thumbnail_id( $calling_post_id ) != $attachment_id ) {
1526 $calling_post = get_post( $calling_post_id );
1527 $calling_post_type_object = get_post_type_object( $calling_post->post_type );
1529 $ajax_nonce = wp_create_nonce( "set_post_thumbnail-$calling_post_id" );
1530 $thumbnail = "<a class='wp-post-thumbnail' id='wp-post-thumbnail-" . $attachment_id . "' href='#' onclick='WPSetAsThumbnail(\"$attachment_id\", \"$ajax_nonce\");return false;'>" . esc_html( $calling_post_type_object->labels->use_featured_image ) . "</a>";
1533 if ( ( $r['send'] || $thumbnail || $delete ) && !isset( $form_fields['buttons'] ) ) {
1534 $form_fields['buttons'] = array( 'tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>" . $r['send'] . " $thumbnail $delete</td></tr>\n" );
1536 $hidden_fields = array();
1538 foreach ( $form_fields as $id => $field ) {
1539 if ( $id[0] == '_' )
1542 if ( !empty( $field['tr'] ) ) {
1543 $item .= $field['tr'];
1547 $field = array_merge( $defaults, $field );
1548 $name = "attachments[$attachment_id][$id]";
1550 if ( $field['input'] == 'hidden' ) {
1551 $hidden_fields[$name] = $field['value'];
1555 $required = $field['required'] ? '<span class="required">*</span>' : '';
1556 $required_attr = $field['required'] ? ' required' : '';
1557 $aria_required = $field['required'] ? " aria-required='true'" : '';
1559 $class .= $field['required'] ? ' form-required' : '';
1561 $item .= "\t\t<tr class='$class'>\n\t\t\t<th scope='row' class='label'><label for='$name'><span class='alignleft'>{$field['label']}{$required}</span><br class='clear' /></label></th>\n\t\t\t<td class='field'>";
1562 if ( !empty( $field[ $field['input'] ] ) )
1563 $item .= $field[ $field['input'] ];
1564 elseif ( $field['input'] == 'textarea' ) {
1565 if ( 'post_content' == $id && user_can_richedit() ) {
1566 // Sanitize_post() skips the post_content when user_can_richedit.
1567 $field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES );
1569 // Post_excerpt is already escaped by sanitize_post() in get_attachment_fields_to_edit().
1570 $item .= "<textarea id='$name' name='$name'{$required_attr}{$aria_required}>" . $field['value'] . '</textarea>';
1572 $item .= "<input type='text' class='text' id='$name' name='$name' value='" . esc_attr( $field['value'] ) . "'{$required_attr}{$aria_required} />";
1574 if ( !empty( $field['helps'] ) )
1575 $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
1576 $item .= "</td>\n\t\t</tr>\n";
1578 $extra_rows = array();
1580 if ( !empty( $field['errors'] ) )
1581 foreach ( array_unique( (array) $field['errors'] ) as $error )
1582 $extra_rows['error'][] = $error;
1584 if ( !empty( $field['extra_rows'] ) )
1585 foreach ( $field['extra_rows'] as $class => $rows )
1586 foreach ( (array) $rows as $html )
1587 $extra_rows[$class][] = $html;
1589 foreach ( $extra_rows as $class => $rows )
1590 foreach ( $rows as $html )
1591 $item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
1594 if ( !empty( $form_fields['_final'] ) )
1595 $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
1596 $item .= "\t</tbody>\n";
1597 $item .= "\t</table>\n";
1599 foreach ( $hidden_fields as $name => $value )
1600 $item .= "\t<input type='hidden' name='$name' id='$name' value='" . esc_attr( $value ) . "' />\n";
1602 if ( $post->post_parent < 1 && isset( $_REQUEST['post_id'] ) ) {
1603 $parent = (int) $_REQUEST['post_id'];
1604 $parent_name = "attachments[$attachment_id][post_parent]";
1605 $item .= "\t<input type='hidden' name='$parent_name' id='$parent_name' value='$parent' />\n";
1614 * @param int $attachment_id
1615 * @param array $args
1618 function get_compat_media_markup( $attachment_id, $args = null ) {
1619 $post = get_post( $attachment_id );
1621 $default_args = array(
1623 'in_modal' => false,
1626 $user_can_edit = current_user_can( 'edit_post', $attachment_id );
1628 $args = wp_parse_args( $args, $default_args );
1630 /** This filter is documented in wp-admin/includes/media.php */
1631 $args = apply_filters( 'get_media_item_args', $args );
1633 $form_fields = array();
1635 if ( $args['in_modal'] ) {
1636 foreach ( get_attachment_taxonomies($post) as $taxonomy ) {
1637 $t = (array) get_taxonomy($taxonomy);
1638 if ( ! $t['public'] || ! $t['show_ui'] )
1640 if ( empty($t['label']) )
1641 $t['label'] = $taxonomy;
1642 if ( empty($t['args']) )
1643 $t['args'] = array();
1645 $terms = get_object_term_cache($post->ID, $taxonomy);
1646 if ( false === $terms )
1647 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
1651 foreach ( $terms as $term )
1652 $values[] = $term->slug;
1653 $t['value'] = join(', ', $values);
1654 $t['taxonomy'] = true;
1656 $form_fields[$taxonomy] = $t;
1660 // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
1661 // The recursive merge is easily traversed with array casting: foreach ( (array) $things as $thing )
1662 $form_fields = array_merge_recursive($form_fields, (array) $args['errors'] );
1664 /** This filter is documented in wp-admin/includes/media.php */
1665 $form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
1667 unset( $form_fields['image-size'], $form_fields['align'], $form_fields['image_alt'],
1668 $form_fields['post_title'], $form_fields['post_excerpt'], $form_fields['post_content'],
1669 $form_fields['url'], $form_fields['menu_order'], $form_fields['image_url'] );
1671 /** This filter is documented in wp-admin/includes/media.php */
1672 $media_meta = apply_filters( 'media_meta', '', $post );
1676 'required' => false,
1678 'extra_rows' => array(),
1679 'show_in_edit' => true,
1680 'show_in_modal' => true,
1683 $hidden_fields = array();
1686 foreach ( $form_fields as $id => $field ) {
1687 if ( $id[0] == '_' )
1690 $name = "attachments[$attachment_id][$id]";
1691 $id_attr = "attachments-$attachment_id-$id";
1693 if ( !empty( $field['tr'] ) ) {
1694 $item .= $field['tr'];
1698 $field = array_merge( $defaults, $field );
1700 if ( ( ! $field['show_in_edit'] && ! $args['in_modal'] ) || ( ! $field['show_in_modal'] && $args['in_modal'] ) )
1703 if ( $field['input'] == 'hidden' ) {
1704 $hidden_fields[$name] = $field['value'];
1708 $readonly = ! $user_can_edit && ! empty( $field['taxonomy'] ) ? " readonly='readonly' " : '';
1709 $required = $field['required'] ? '<span class="required">*</span>' : '';
1710 $required_attr = $field['required'] ? ' required' : '';
1711 $aria_required = $field['required'] ? " aria-required='true'" : '';
1712 $class = 'compat-field-' . $id;
1713 $class .= $field['required'] ? ' form-required' : '';
1715 $item .= "\t\t<tr class='$class'>";
1716 $item .= "\t\t\t<th scope='row' class='label'><label for='$id_attr'><span class='alignleft'>{$field['label']}</span>$required<br class='clear' /></label>";
1717 $item .= "</th>\n\t\t\t<td class='field'>";
1719 if ( !empty( $field[ $field['input'] ] ) )
1720 $item .= $field[ $field['input'] ];
1721 elseif ( $field['input'] == 'textarea' ) {
1722 if ( 'post_content' == $id && user_can_richedit() ) {
1723 // sanitize_post() skips the post_content when user_can_richedit.
1724 $field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES );
1726 $item .= "<textarea id='$id_attr' name='$name'{$required_attr}{$aria_required}>" . $field['value'] . '</textarea>';
1728 $item .= "<input type='text' class='text' id='$id_attr' name='$name' value='" . esc_attr( $field['value'] ) . "' $readonly{$required_attr}{$aria_required} />";
1730 if ( !empty( $field['helps'] ) )
1731 $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
1732 $item .= "</td>\n\t\t</tr>\n";
1734 $extra_rows = array();
1736 if ( !empty( $field['errors'] ) )
1737 foreach ( array_unique( (array) $field['errors'] ) as $error )
1738 $extra_rows['error'][] = $error;
1740 if ( !empty( $field['extra_rows'] ) )
1741 foreach ( $field['extra_rows'] as $class => $rows )
1742 foreach ( (array) $rows as $html )
1743 $extra_rows[$class][] = $html;
1745 foreach ( $extra_rows as $class => $rows )
1746 foreach ( $rows as $html )
1747 $item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
1750 if ( !empty( $form_fields['_final'] ) )
1751 $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
1754 $item = '<p class="media-types media-types-required-info">' .
1755 sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) . '</p>
1756 <table class="compat-attachment-fields">' . $item . '</table>';
1759 foreach ( $hidden_fields as $hidden_field => $value ) {
1760 $item .= '<input type="hidden" name="' . esc_attr( $hidden_field ) . '" value="' . esc_attr( $value ) . '" />' . "\n";
1764 $item = '<input type="hidden" name="attachments[' . $attachment_id . '][menu_order]" value="' . esc_attr( $post->menu_order ) . '" />' . $item;
1768 'meta' => $media_meta,
1773 * Outputs the legacy media upload header.
1777 function media_upload_header() {
1778 $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
1780 echo '<script type="text/javascript">post_id = ' . $post_id . ';</script>';
1781 if ( empty( $_GET['chromeless'] ) ) {
1782 echo '<div id="media-upload-header">';
1783 the_media_upload_tabs();
1789 * Outputs the legacy media upload form.
1793 * @global string $type
1794 * @global string $tab
1795 * @global bool $is_IE
1796 * @global bool $is_opera
1798 * @param array $errors
1800 function media_upload_form( $errors = null ) {
1801 global $type, $tab, $is_IE, $is_opera;
1803 if ( ! _device_can_upload() ) {
1804 echo '<p>' . sprintf( __('The web browser on your device cannot be used to upload files. You may be able to use the <a href="%s">native app for your device</a> instead.'), 'https://apps.wordpress.org/' ) . '</p>';
1808 $upload_action_url = admin_url('async-upload.php');
1809 $post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0;
1810 $_type = isset($type) ? $type : '';
1811 $_tab = isset($tab) ? $tab : '';
1813 $max_upload_size = wp_max_upload_size();
1814 if ( ! $max_upload_size ) {
1815 $max_upload_size = 0;
1819 <div id="media-upload-notice"><?php
1821 if (isset($errors['upload_notice']) )
1822 echo $errors['upload_notice'];
1825 <div id="media-upload-error"><?php
1827 if (isset($errors['upload_error']) && is_wp_error($errors['upload_error']))
1828 echo $errors['upload_error']->get_error_message();
1832 if ( is_multisite() && !is_upload_space_available() ) {
1834 * Fires when an upload will exceed the defined upload space quota for a network site.
1838 do_action( 'upload_ui_over_quota' );
1843 * Fires just before the legacy (pre-3.5.0) upload interface is loaded.
1847 do_action( 'pre-upload-ui' );
1849 $post_params = array(
1850 "post_id" => $post_id,
1851 "_wpnonce" => wp_create_nonce('media-form'),
1858 * Filters the media upload post parameters.
1860 * @since 3.1.0 As 'swfupload_post_params'
1863 * @param array $post_params An array of media upload parameters used by Plupload.
1865 $post_params = apply_filters( 'upload_post_params', $post_params );
1867 $plupload_init = array(
1868 'runtimes' => 'html5,flash,silverlight,html4',
1869 'browse_button' => 'plupload-browse-button',
1870 'container' => 'plupload-upload-ui',
1871 'drop_element' => 'drag-drop-area',
1872 'file_data_name' => 'async-upload',
1873 'url' => $upload_action_url,
1874 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
1875 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
1877 'max_file_size' => $max_upload_size . 'b',
1879 'multipart_params' => $post_params,
1882 // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
1883 // when enabled. See #29602.
1884 if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
1885 strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
1887 $plupload_init['multi_selection'] = false;
1891 * Filters the default Plupload settings.
1895 * @param array $plupload_init An array of default settings used by Plupload.
1897 $plupload_init = apply_filters( 'plupload_init', $plupload_init );
1901 <script type="text/javascript">
1903 // Verify size is an int. If not return default value.
1904 $large_size_h = absint( get_option('large_size_h') );
1905 if( !$large_size_h )
1906 $large_size_h = 1024;
1907 $large_size_w = absint( get_option('large_size_w') );
1908 if( !$large_size_w )
1909 $large_size_w = 1024;
1911 var resize_height = <?php echo $large_size_h; ?>, resize_width = <?php echo $large_size_w; ?>,
1912 wpUploaderInit = <?php echo wp_json_encode( $plupload_init ); ?>;
1915 <div id="plupload-upload-ui" class="hide-if-no-js">
1918 * Fires before the upload interface loads.
1920 * @since 2.6.0 As 'pre-flash-upload-ui'
1923 do_action( 'pre-plupload-upload-ui' ); ?>
1924 <div id="drag-drop-area">
1925 <div class="drag-drop-inside">
1926 <p class="drag-drop-info"><?php _e('Drop files here'); ?></p>
1927 <p><?php _ex('or', 'Uploader: Drop files here - or - Select Files'); ?></p>
1928 <p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php esc_attr_e('Select Files'); ?>" class="button" /></p>
1933 * Fires after the upload interface loads.
1935 * @since 2.6.0 As 'post-flash-upload-ui'
1938 do_action( 'post-plupload-upload-ui' ); ?>
1941 <div id="html-upload-ui" class="hide-if-js">
1944 * Fires before the upload button in the media upload interface.
1948 do_action( 'pre-html-upload-ui' );
1950 <p id="async-upload-wrap">
1951 <label class="screen-reader-text" for="async-upload"><?php _e('Upload'); ?></label>
1952 <input type="file" name="async-upload" id="async-upload" />
1953 <?php submit_button( __( 'Upload' ), 'primary', 'html-upload', false ); ?>
1954 <a href="#" onclick="try{top.tb_remove();}catch(e){}; return false;"><?php _e('Cancel'); ?></a>
1956 <div class="clear"></div>
1959 * Fires after the upload button in the media upload interface.
1963 do_action( 'post-html-upload-ui' );
1967 <p class="max-upload-size"><?php printf( __( 'Maximum upload file size: %s.' ), esc_html( size_format( $max_upload_size ) ) ); ?></p>
1971 * Fires on the post upload UI screen.
1973 * Legacy (pre-3.5.0) media workflow hook.
1977 do_action( 'post-upload-ui' );
1981 * Outputs the legacy media upload form for a given media type.
1985 * @param string $type
1986 * @param object $errors
1987 * @param integer $id
1989 function media_upload_type_form($type = 'file', $errors = null, $id = null) {
1991 media_upload_header();
1993 $post_id = isset( $_REQUEST['post_id'] )? intval( $_REQUEST['post_id'] ) : 0;
1995 $form_action_url = admin_url("media-upload.php?type=$type&tab=type&post_id=$post_id");
1998 * Filters the media upload form action URL.
2002 * @param string $form_action_url The media upload form action URL.
2003 * @param string $type The type of media. Default 'file'.
2005 $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2006 $form_class = 'media-upload-form type-form validate';
2008 if ( get_user_setting('uploader') )
2009 $form_class .= ' html-uploader';
2012 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
2013 <?php submit_button( '', 'hidden', 'save', false ); ?>
2014 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2015 <?php wp_nonce_field('media-form'); ?>
2017 <h3 class="media-title"><?php _e('Add media files from your computer'); ?></h3>
2019 <?php media_upload_form( $errors ); ?>
2021 <script type="text/javascript">
2023 var preloaded = $(".media-item.preloaded");
2024 if ( preloaded.length > 0 ) {
2025 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2030 <div id="media-items"><?php
2033 if ( !is_wp_error($id) ) {
2034 add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2);
2035 echo get_media_items( $id, $errors );
2037 echo '<div id="media-upload-error">'.esc_html($id->get_error_message()).'</div></div>';
2043 <p class="savebutton ml-submit">
2044 <?php submit_button( __( 'Save all changes' ), '', 'save', false ); ?>
2051 * Outputs the legacy media upload form for external media.
2055 * @param string $type
2056 * @param object $errors
2057 * @param integer $id
2059 function media_upload_type_url_form($type = null, $errors = null, $id = null) {
2060 if ( null === $type )
2063 media_upload_header();
2065 $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2067 $form_action_url = admin_url("media-upload.php?type=$type&tab=type&post_id=$post_id");
2068 /** This filter is documented in wp-admin/includes/media.php */
2069 $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2070 $form_class = 'media-upload-form type-form validate';
2072 if ( get_user_setting('uploader') )
2073 $form_class .= ' html-uploader';
2076 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
2077 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2078 <?php wp_nonce_field('media-form'); ?>
2080 <h3 class="media-title"><?php _e('Insert media from another website'); ?></h3>
2082 <script type="text/javascript">
2087 align : 'alignnone',
2089 insert : function() {
2090 var t = this, html, f = document.forms[0], cls, title = '', alt = '', caption = '';
2092 if ( '' == f.src.value || '' == t.width )
2096 alt = f.alt.value.replace(/'/g, ''').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
2099 /** This filter is documented in wp-admin/includes/media.php */
2100 if ( ! apply_filters( 'disable_captions', '' ) ) {
2102 if ( f.caption.value ) {
2103 caption = f.caption.value.replace(/\r\n|\r/g, '\n');
2104 caption = caption.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){
2105 return a.replace(/[\r\n\t]+/, ' ');
2108 caption = caption.replace(/\s*\n\s*/g, '<br />');
2112 cls = caption ? '' : ' class="'+t.align+'"';
2114 html = '<img alt="'+alt+'" src="'+f.src.value+'"'+cls+' width="'+t.width+'" height="'+t.height+'" />';
2116 if ( f.url.value ) {
2117 url = f.url.value.replace(/'/g, ''').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
2118 html = '<a href="'+url+'">'+html+'</a>';
2122 html = '[caption id="" align="'+t.align+'" width="'+t.width+'"]'+html+caption+'[/caption]';
2124 var win = window.dialogArguments || opener || parent || top;
2125 win.send_to_editor(html);
2129 resetImageData : function() {
2130 var t = addExtImage;
2132 t.width = t.height = '';
2133 document.getElementById('go_button').style.color = '#bbb';
2134 if ( ! document.forms[0].src.value )
2135 document.getElementById('status_img').innerHTML = '';
2136 else document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/no.png' ) ); ?>" alt="" />';
2139 updateImageData : function() {
2140 var t = addExtImage;
2142 t.width = t.preloadImg.width;
2143 t.height = t.preloadImg.height;
2144 document.getElementById('go_button').style.color = '#333';
2145 document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/yes.png' ) ); ?>" alt="" />';
2148 getImageData : function() {
2149 if ( jQuery('table.describe').hasClass('not-image') )
2152 var t = addExtImage, src = document.forms[0].src.value;
2159 document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/spinner-2x.gif' ) ); ?>" alt="" width="16" height="16" />';
2160 t.preloadImg = new Image();
2161 t.preloadImg.onload = t.updateImageData;
2162 t.preloadImg.onerror = t.resetImageData;
2163 t.preloadImg.src = src;
2167 jQuery(document).ready( function($) {
2168 $('.media-types input').click( function() {
2169 $('table.describe').toggleClass('not-image', $('#not-image').prop('checked') );
2174 <div id="media-items">
2175 <div class="media-item media-blank">
2178 * Filters the insert media from URL form HTML.
2182 * @param string $form_html The insert from URL form HTML.
2184 echo apply_filters( 'type_url_form_media', wp_media_insert_url_form( $type ) );
2193 * Adds gallery form to upload iframe
2197 * @global string $redir_tab
2198 * @global string $type
2199 * @global string $tab
2201 * @param array $errors
2203 function media_upload_gallery_form($errors) {
2204 global $redir_tab, $type;
2206 $redir_tab = 'gallery';
2207 media_upload_header();
2209 $post_id = intval($_REQUEST['post_id']);
2210 $form_action_url = admin_url("media-upload.php?type=$type&tab=gallery&post_id=$post_id");
2211 /** This filter is documented in wp-admin/includes/media.php */
2212 $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2213 $form_class = 'media-upload-form validate';
2215 if ( get_user_setting('uploader') )
2216 $form_class .= ' html-uploader';
2219 <script type="text/javascript">
2221 var preloaded = $(".media-item.preloaded");
2222 if ( preloaded.length > 0 ) {
2223 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2228 <div id="sort-buttons" class="hide-if-no-js">
2230 <?php _e('All Tabs:'); ?>
2231 <a href="#" id="showall"><?php _e('Show'); ?></a>
2232 <a href="#" id="hideall" style="display:none;"><?php _e('Hide'); ?></a>
2234 <?php _e('Sort Order:'); ?>
2235 <a href="#" id="asc"><?php _e('Ascending'); ?></a> |
2236 <a href="#" id="desc"><?php _e('Descending'); ?></a> |
2237 <a href="#" id="clear"><?php _ex('Clear', 'verb'); ?></a>
2239 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="gallery-form">
2240 <?php wp_nonce_field('media-form'); ?>
2241 <?php //media_upload_form( $errors ); ?>
2242 <table class="widefat">
2244 <th><?php _e('Media'); ?></th>
2245 <th class="order-head"><?php _e('Order'); ?></th>
2246 <th class="actions-head"><?php _e('Actions'); ?></th>
2249 <div id="media-items">
2250 <?php add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); ?>
2251 <?php echo get_media_items($post_id, $errors); ?>
2254 <p class="ml-submit">
2255 <?php submit_button( __( 'Save all changes' ), 'savebutton', 'save', false, array( 'id' => 'save-all', 'style' => 'display: none;' ) ); ?>
2256 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2257 <input type="hidden" name="type" value="<?php echo esc_attr( $GLOBALS['type'] ); ?>" />
2258 <input type="hidden" name="tab" value="<?php echo esc_attr( $GLOBALS['tab'] ); ?>" />
2261 <div id="gallery-settings" style="display:none;">
2262 <div class="title"><?php _e('Gallery Settings'); ?></div>
2263 <table id="basic" class="describe"><tbody>
2265 <th scope="row" class="label">
2267 <span class="alignleft"><?php _e('Link thumbnails to:'); ?></span>
2271 <input type="radio" name="linkto" id="linkto-file" value="file" />
2272 <label for="linkto-file" class="radio"><?php _e('Image File'); ?></label>
2274 <input type="radio" checked="checked" name="linkto" id="linkto-post" value="post" />
2275 <label for="linkto-post" class="radio"><?php _e('Attachment Page'); ?></label>
2280 <th scope="row" class="label">
2282 <span class="alignleft"><?php _e('Order images by:'); ?></span>
2286 <select id="orderby" name="orderby">
2287 <option value="menu_order" selected="selected"><?php _e('Menu order'); ?></option>
2288 <option value="title"><?php _e('Title'); ?></option>
2289 <option value="post_date"><?php _e('Date/Time'); ?></option>
2290 <option value="rand"><?php _e('Random'); ?></option>
2296 <th scope="row" class="label">
2298 <span class="alignleft"><?php _e('Order:'); ?></span>
2302 <input type="radio" checked="checked" name="order" id="order-asc" value="asc" />
2303 <label for="order-asc" class="radio"><?php _e('Ascending'); ?></label>
2305 <input type="radio" name="order" id="order-desc" value="desc" />
2306 <label for="order-desc" class="radio"><?php _e('Descending'); ?></label>
2311 <th scope="row" class="label">
2313 <span class="alignleft"><?php _e('Gallery columns:'); ?></span>
2317 <select id="columns" name="columns">
2318 <option value="1">1</option>
2319 <option value="2">2</option>
2320 <option value="3" selected="selected">3</option>
2321 <option value="4">4</option>
2322 <option value="5">5</option>
2323 <option value="6">6</option>
2324 <option value="7">7</option>
2325 <option value="8">8</option>
2326 <option value="9">9</option>
2332 <p class="ml-submit">
2333 <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="insert-gallery" id="insert-gallery" value="<?php esc_attr_e( 'Insert gallery' ); ?>" />
2334 <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="update-gallery" id="update-gallery" value="<?php esc_attr_e( 'Update gallery settings' ); ?>" />
2342 * Outputs the legacy media upload form for the media library.
2346 * @global wpdb $wpdb
2347 * @global WP_Query $wp_query
2348 * @global WP_Locale $wp_locale
2349 * @global string $type
2350 * @global string $tab
2351 * @global array $post_mime_types
2353 * @param array $errors
2355 function media_upload_library_form($errors) {
2356 global $wpdb, $wp_query, $wp_locale, $type, $tab, $post_mime_types;
2358 media_upload_header();
2360 $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2362 $form_action_url = admin_url("media-upload.php?type=$type&tab=library&post_id=$post_id");
2363 /** This filter is documented in wp-admin/includes/media.php */
2364 $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2365 $form_class = 'media-upload-form validate';
2367 if ( get_user_setting('uploader') )
2368 $form_class .= ' html-uploader';
2371 $q['posts_per_page'] = 10;
2372 $q['paged'] = isset( $q['paged'] ) ? intval( $q['paged'] ) : 0;
2373 if ( $q['paged'] < 1 ) {
2376 $q['offset'] = ( $q['paged'] - 1 ) * 10;
2377 if ( $q['offset'] < 1 ) {
2381 list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query( $q );
2385 <form id="filter" method="get">
2386 <input type="hidden" name="type" value="<?php echo esc_attr( $type ); ?>" />
2387 <input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>" />
2388 <input type="hidden" name="post_id" value="<?php echo (int) $post_id; ?>" />
2389 <input type="hidden" name="post_mime_type" value="<?php echo isset( $_GET['post_mime_type'] ) ? esc_attr( $_GET['post_mime_type'] ) : ''; ?>" />
2390 <input type="hidden" name="context" value="<?php echo isset( $_GET['context'] ) ? esc_attr( $_GET['context'] ) : ''; ?>" />
2392 <p id="media-search" class="search-box">
2393 <label class="screen-reader-text" for="media-search-input"><?php _e('Search Media');?>:</label>
2394 <input type="search" id="media-search-input" name="s" value="<?php the_search_query(); ?>" />
2395 <?php submit_button( __( 'Search Media' ), '', '', false ); ?>
2398 <ul class="subsubsub">
2400 $type_links = array();
2401 $_num_posts = (array) wp_count_attachments();
2402 $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
2403 foreach ( $matches as $_type => $reals )
2404 foreach ( $reals as $real )
2405 if ( isset($num_posts[$_type]) )
2406 $num_posts[$_type] += $_num_posts[$real];
2408 $num_posts[$_type] = $_num_posts[$real];
2409 // If available type specified by media button clicked, filter by that type
2410 if ( empty($_GET['post_mime_type']) && !empty($num_posts[$type]) ) {
2411 $_GET['post_mime_type'] = $type;
2412 list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
2414 if ( empty($_GET['post_mime_type']) || $_GET['post_mime_type'] == 'all' )
2415 $class = ' class="current"';
2418 $type_links[] = '<li><a href="' . esc_url(add_query_arg(array('post_mime_type'=>'all', 'paged'=>false, 'm'=>false))) . '"' . $class . '>' . __('All Types') . '</a>';
2419 foreach ( $post_mime_types as $mime_type => $label ) {
2422 if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
2425 if ( isset($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
2426 $class = ' class="current"';
2428 $type_links[] = '<li><a href="' . esc_url(add_query_arg(array('post_mime_type'=>$mime_type, 'paged'=>false))) . '"' . $class . '>' . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), '<span id="' . $mime_type . '-counter">' . number_format_i18n( $num_posts[$mime_type] ) . '</span>') . '</a>';
2431 * Filters the media upload mime type list items.
2433 * Returned values should begin with an `<li>` tag.
2437 * @param array $type_links An array of list items containing mime type link HTML.
2439 echo implode(' | </li>', apply_filters( 'media_upload_mime_type_links', $type_links ) ) . '</li>';
2444 <div class="tablenav">
2447 $page_links = paginate_links( array(
2448 'base' => add_query_arg( 'paged', '%#%' ),
2450 'prev_text' => __('«'),
2451 'next_text' => __('»'),
2452 'total' => ceil($wp_query->found_posts / 10),
2453 'current' => $q['paged'],
2457 echo "<div class='tablenav-pages'>$page_links</div>";
2460 <div class="alignleft actions">
2463 $arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM $wpdb->posts WHERE post_type = 'attachment' ORDER BY post_date DESC";
2465 $arc_result = $wpdb->get_results( $arc_query );
2467 $month_count = count($arc_result);
2468 $selected_month = isset( $_GET['m'] ) ? $_GET['m'] : 0;
2470 if ( $month_count && !( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) { ?>
2472 <option<?php selected( $selected_month, 0 ); ?> value='0'><?php _e( 'All dates' ); ?></option>
2474 foreach ($arc_result as $arc_row) {
2475 if ( $arc_row->yyear == 0 )
2477 $arc_row->mmonth = zeroise( $arc_row->mmonth, 2 );
2479 if ( $arc_row->yyear . $arc_row->mmonth == $selected_month )
2480 $default = ' selected="selected"';
2484 echo "<option$default value='" . esc_attr( $arc_row->yyear . $arc_row->mmonth ) . "'>";
2485 echo esc_html( $wp_locale->get_month($arc_row->mmonth) . " $arc_row->yyear" );
2492 <?php submit_button( __( 'Filter »' ), '', 'post-query-submit', false ); ?>
2496 <br class="clear" />
2500 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="library-form">
2502 <?php wp_nonce_field('media-form'); ?>
2503 <?php //media_upload_form( $errors ); ?>
2505 <script type="text/javascript">
2508 var preloaded = $(".media-item.preloaded");
2509 if ( preloaded.length > 0 ) {
2510 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2517 <div id="media-items">
2518 <?php add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); ?>
2519 <?php echo get_media_items(null, $errors); ?>
2521 <p class="ml-submit">
2522 <?php submit_button( __( 'Save all changes' ), 'savebutton', 'save', false ); ?>
2523 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2530 * Creates the form for external url
2534 * @param string $default_view
2535 * @return string the form html
2537 function wp_media_insert_url_form( $default_view = 'image' ) {
2538 /** This filter is documented in wp-admin/includes/media.php */
2539 if ( ! apply_filters( 'disable_captions', '' ) ) {
2541 <tr class="image-only">
2542 <th scope="row" class="label">
2543 <label for="caption"><span class="alignleft">' . __('Image Caption') . '</span></label>
2545 <td class="field"><textarea id="caption" name="caption"></textarea></td>
2552 $default_align = get_option('image_default_align');
2553 if ( empty($default_align) )
2554 $default_align = 'none';
2556 if ( 'image' == $default_view ) {
2557 $view = 'image-only';
2560 $view = $table_class = 'not-image';
2564 <p class="media-types"><label><input type="radio" name="media_type" value="image" id="image-only"' . checked( 'image-only', $view, false ) . ' /> ' . __( 'Image' ) . '</label> <label><input type="radio" name="media_type" value="generic" id="not-image"' . checked( 'not-image', $view, false ) . ' /> ' . __( 'Audio, Video, or Other File' ) . '</label></p>
2565 <p class="media-types media-types-required-info">' . sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) . '</p>
2566 <table class="describe ' . $table_class . '"><tbody>
2568 <th scope="row" class="label" style="width:130px;">
2569 <label for="src"><span class="alignleft">' . __( 'URL' ) . '</span> <span class="required">*</span></label>
2570 <span class="alignright" id="status_img"></span>
2572 <td class="field"><input id="src" name="src" value="" type="text" required aria-required="true" onblur="addExtImage.getImageData()" /></td>
2576 <th scope="row" class="label">
2577 <label for="title"><span class="alignleft">' . __( 'Title' ) . '</span> <span class="required">*</span></label>
2579 <td class="field"><input id="title" name="title" value="" type="text" required aria-required="true" /></td>
2582 <tr class="not-image"><td></td><td><p class="help">' . __('Link text, e.g. “Ransom Demands (PDF)”') . '</p></td></tr>
2584 <tr class="image-only">
2585 <th scope="row" class="label">
2586 <label for="alt"><span class="alignleft">' . __('Alternative Text') . '</span></label>
2588 <td class="field"><input id="alt" name="alt" value="" type="text" aria-required="true" />
2589 <p class="help">' . __('Alt text for the image, e.g. “The Mona Lisa”') . '</p></td>
2592 <tr class="align image-only">
2593 <th scope="row" class="label"><p><label for="align">' . __('Alignment') . '</label></p></th>
2595 <input name="align" id="align-none" value="none" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'none' ? ' checked="checked"' : '').' />
2596 <label for="align-none" class="align image-align-none-label">' . __('None') . '</label>
2597 <input name="align" id="align-left" value="left" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'left' ? ' checked="checked"' : '').' />
2598 <label for="align-left" class="align image-align-left-label">' . __('Left') . '</label>
2599 <input name="align" id="align-center" value="center" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'center' ? ' checked="checked"' : '').' />
2600 <label for="align-center" class="align image-align-center-label">' . __('Center') . '</label>
2601 <input name="align" id="align-right" value="right" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'right' ? ' checked="checked"' : '').' />
2602 <label for="align-right" class="align image-align-right-label">' . __('Right') . '</label>
2606 <tr class="image-only">
2607 <th scope="row" class="label">
2608 <label for="url"><span class="alignleft">' . __('Link Image To:') . '</span></label>
2610 <td class="field"><input id="url" name="url" value="" type="text" /><br />
2612 <button type="button" class="button" value="" onclick="document.forms[0].url.value=null">' . __('None') . '</button>
2613 <button type="button" class="button" value="" onclick="document.forms[0].url.value=document.forms[0].src.value">' . __('Link to image') . '</button>
2614 <p class="help">' . __('Enter a link URL or click above for presets.') . '</p></td>
2616 <tr class="image-only">
2619 <input type="button" class="button" id="go_button" style="color:#bbb;" onclick="addExtImage.insert()" value="' . esc_attr__('Insert into Post') . '" />
2622 <tr class="not-image">
2625 ' . get_submit_button( __( 'Insert into Post' ), '', 'insertonlybutton', false ) . '
2634 * Displays the multi-file uploader message.
2638 * @global int $post_ID
2640 function media_upload_flash_bypass() {
2641 $browser_uploader = admin_url( 'media-new.php?browser-uploader' );
2643 if ( $post = get_post() )
2644 $browser_uploader .= '&post_id=' . intval( $post->ID );
2645 elseif ( ! empty( $GLOBALS['post_ID'] ) )
2646 $browser_uploader .= '&post_id=' . intval( $GLOBALS['post_ID'] );
2649 <p class="upload-flash-bypass">
2650 <?php printf( __( 'You are using the multi-file uploader. Problems? Try the <a href="%1$s" target="%2$s">browser uploader</a> instead.' ), $browser_uploader, '_blank' ); ?>
2656 * Displays the browser's built-in uploader message.
2660 function media_upload_html_bypass() {
2662 <p class="upload-html-bypass hide-if-no-js">
2663 <?php _e('You are using the browser’s built-in file uploader. The WordPress uploader includes multiple file selection and drag and drop capability. <a href="#">Switch to the multi-file uploader</a>.'); ?>
2669 * Used to display a "After a file has been uploaded..." help message.
2673 function media_upload_text_after() {}
2676 * Displays the checkbox to scale images.
2680 function media_upload_max_image_resize() {
2681 $checked = get_user_setting('upload_resize') ? ' checked="true"' : '';
2684 if ( current_user_can( 'manage_options' ) ) {
2685 $a = '<a href="' . esc_url( admin_url( 'options-media.php' ) ) . '" target="_blank">';
2689 <p class="hide-if-no-js"><label>
2690 <input name="image_resize" type="checkbox" id="image_resize" value="true"<?php echo $checked; ?> />
2692 /* translators: %1$s is link start tag, %2$s is link end tag, %3$d is width, %4$d is height*/
2693 printf( __( 'Scale images to match the large size selected in %1$simage options%2$s (%3$d × %4$d).' ), $a, $end, (int) get_option( 'large_size_w', '1024' ), (int) get_option( 'large_size_h', '1024' ) );
2700 * Displays the out of storage quota message in Multisite.
2704 function multisite_over_quota_message() {
2705 echo '<p>' . sprintf( __( 'Sorry, you have used all of your storage quota of %s MB.' ), get_space_allowed() ) . '</p>';
2709 * Displays the image and editor in the post editor
2713 * @param WP_Post $post A post object.
2715 function edit_form_image_editor( $post ) {
2716 $open = isset( $_GET['image-editor'] );
2718 require_once ABSPATH . 'wp-admin/includes/image-edit.php';
2721 if ( $attachment_id = intval( $post->ID ) )
2722 $thumb_url = wp_get_attachment_image_src( $attachment_id, array( 900, 450 ), true );
2724 $alt_text = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
2726 $att_url = wp_get_attachment_url( $post->ID ); ?>
2727 <div class="wp_attachment_holder wp-clearfix">
2729 if ( wp_attachment_is_image( $post->ID ) ) :
2730 $image_edit_button = '';
2731 if ( wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) {
2732 $nonce = wp_create_nonce( "image_editor-$post->ID" );
2733 $image_edit_button = "<input type='button' id='imgedit-open-btn-$post->ID' onclick='imageEdit.open( $post->ID, \"$nonce\" )' class='button' value='" . esc_attr__( 'Edit Image' ) . "' /> <span class='spinner'></span>";
2737 <div class="imgedit-response" id="imgedit-response-<?php echo $attachment_id; ?>"></div>
2739 <div<?php if ( $open ) echo ' style="display:none"'; ?> class="wp_attachment_image wp-clearfix" id="media-head-<?php echo $attachment_id; ?>">
2740 <p id="thumbnail-head-<?php echo $attachment_id; ?>"><img class="thumbnail" src="<?php echo set_url_scheme( $thumb_url[0] ); ?>" style="max-width:100%" alt="" /></p>
2741 <p><?php echo $image_edit_button; ?></p>
2743 <div<?php if ( ! $open ) echo ' style="display:none"'; ?> class="image-editor" id="image-editor-<?php echo $attachment_id; ?>">
2744 <?php if ( $open ) wp_image_editor( $attachment_id ); ?>
2747 elseif ( $attachment_id && wp_attachment_is( 'audio', $post ) ):
2749 wp_maybe_generate_attachment_metadata( $post );
2751 echo wp_audio_shortcode( array( 'src' => $att_url ) );
2753 elseif ( $attachment_id && wp_attachment_is( 'video', $post ) ):
2755 wp_maybe_generate_attachment_metadata( $post );
2757 $meta = wp_get_attachment_metadata( $attachment_id );
2758 $w = ! empty( $meta['width'] ) ? min( $meta['width'], 640 ) : 0;
2759 $h = ! empty( $meta['height'] ) ? $meta['height'] : 0;
2760 if ( $h && $w < $meta['width'] ) {
2761 $h = round( ( $meta['height'] * $w ) / $meta['width'] );
2764 $attr = array( 'src' => $att_url );
2765 if ( ! empty( $w ) && ! empty( $h ) ) {
2766 $attr['width'] = $w;
2767 $attr['height'] = $h;
2770 $thumb_id = get_post_thumbnail_id( $attachment_id );
2771 if ( ! empty( $thumb_id ) ) {
2772 $attr['poster'] = wp_get_attachment_url( $thumb_id );
2775 echo wp_video_shortcode( $attr );
2777 elseif ( isset( $thumb_url[0] ) ):
2780 <div class="wp_attachment_image wp-clearfix" id="media-head-<?php echo $attachment_id; ?>">
2781 <p id="thumbnail-head-<?php echo $attachment_id; ?>">
2782 <img class="thumbnail" src="<?php echo set_url_scheme( $thumb_url[0] ); ?>" style="max-width:100%" alt="" />
2790 * Fires when an attachment type can't be rendered in the edit form.
2794 * @param WP_Post $post A post object.
2796 do_action( 'wp_edit_form_attachment_display', $post );
2800 <div class="wp_attachment_details edit-form-section">
2802 <label for="attachment_caption"><strong><?php _e( 'Caption' ); ?></strong></label><br />
2803 <textarea class="widefat" name="excerpt" id="attachment_caption"><?php echo $post->post_excerpt; ?></textarea>
2807 <?php if ( 'image' === substr( $post->post_mime_type, 0, 5 ) ) : ?>
2809 <label for="attachment_alt"><strong><?php _e( 'Alternative Text' ); ?></strong></label><br />
2810 <input type="text" class="widefat" name="_wp_attachment_image_alt" id="attachment_alt" value="<?php echo esc_attr( $alt_text ); ?>" />
2815 $quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,close' );
2816 $editor_args = array(
2817 'textarea_name' => 'content',
2818 'textarea_rows' => 5,
2819 'media_buttons' => false,
2821 'quicktags' => $quicktags_settings,
2825 <label for="attachment_content"><strong><?php _e( 'Description' ); ?></strong><?php
2826 if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
2827 echo ': ' . __( 'Displayed on attachment pages.' );
2829 <?php wp_editor( $post->post_content, 'attachment_content', $editor_args ); ?>
2833 $extras = get_compat_media_markup( $post->ID );
2834 echo $extras['item'];
2835 echo '<input type="hidden" id="image-edit-context" value="edit-attachment" />' . "\n";
2839 * Displays non-editable attachment metadata in the publish meta box.
2843 function attachment_submitbox_metadata() {
2846 $file = get_attached_file( $post->ID );
2847 $filename = esc_html( wp_basename( $file ) );
2850 $meta = wp_get_attachment_metadata( $post->ID );
2851 if ( isset( $meta['width'], $meta['height'] ) )
2852 $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']} × {$meta['height']}</span> ";
2853 /** This filter is documented in wp-admin/includes/media.php */
2854 $media_dims = apply_filters( 'media_meta', $media_dims, $post );
2856 $att_url = wp_get_attachment_url( $post->ID );
2858 <div class="misc-pub-section misc-pub-attachment">
2859 <label for="attachment_url"><?php _e( 'File URL:' ); ?></label>
2860 <input type="text" class="widefat urlfield" readonly="readonly" name="attachment_url" id="attachment_url" value="<?php echo esc_attr( $att_url ); ?>" />
2862 <div class="misc-pub-section misc-pub-filename">
2863 <?php _e( 'File name:' ); ?> <strong><?php echo $filename; ?></strong>
2865 <div class="misc-pub-section misc-pub-filetype">
2866 <?php _e( 'File type:' ); ?> <strong><?php
2867 if ( preg_match( '/^.*?\.(\w+)$/', get_attached_file( $post->ID ), $matches ) ) {
2868 echo esc_html( strtoupper( $matches[1] ) );
2869 list( $mime_type ) = explode( '/', $post->post_mime_type );
2870 if ( $mime_type !== 'image' && ! empty( $meta['mime_type'] ) ) {
2871 if ( $meta['mime_type'] !== "$mime_type/" . strtolower( $matches[1] ) ) {
2872 echo ' (' . $meta['mime_type'] . ')';
2876 echo strtoupper( str_replace( 'image/', '', $post->post_mime_type ) );
2884 if ( isset( $meta['filesize'] ) )
2885 $file_size = $meta['filesize'];
2886 elseif ( file_exists( $file ) )
2887 $file_size = filesize( $file );
2889 if ( ! empty( $file_size ) ) : ?>
2890 <div class="misc-pub-section misc-pub-filesize">
2891 <?php _e( 'File size:' ); ?> <strong><?php echo size_format( $file_size ); ?></strong>
2896 if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
2899 * Filters the audio and video metadata fields to be shown in the publish meta box.
2901 * The key for each item in the array should correspond to an attachment
2902 * metadata key, and the value should be the desired label.
2906 * @param array $fields An array of the attachment metadata keys and labels.
2908 $fields = apply_filters( 'media_submitbox_misc_sections', array(
2909 'length_formatted' => __( 'Length:' ),
2910 'bitrate' => __( 'Bitrate:' ),
2913 foreach ( $fields as $key => $label ) {
2914 if ( empty( $meta[ $key ] ) ) {
2918 <div class="misc-pub-section misc-pub-mime-meta misc-pub-<?php echo sanitize_html_class( $key ); ?>">
2919 <?php echo $label ?> <strong><?php
2922 echo round( $meta['bitrate'] / 1000 ) . 'kb/s';
2923 if ( ! empty( $meta['bitrate_mode'] ) ) {
2924 echo ' ' . strtoupper( esc_html( $meta['bitrate_mode'] ) );
2928 echo esc_html( $meta[ $key ] );
2937 * Filters the audio attachment metadata fields to be shown in the publish meta box.
2939 * The key for each item in the array should correspond to an attachment
2940 * metadata key, and the value should be the desired label.
2944 * @param array $fields An array of the attachment metadata keys and labels.
2946 $audio_fields = apply_filters( 'audio_submitbox_misc_sections', array(
2947 'dataformat' => __( 'Audio Format:' ),
2948 'codec' => __( 'Audio Codec:' )
2951 foreach ( $audio_fields as $key => $label ) {
2952 if ( empty( $meta['audio'][ $key ] ) ) {
2956 <div class="misc-pub-section misc-pub-audio misc-pub-<?php echo sanitize_html_class( $key ); ?>">
2957 <?php echo $label; ?> <strong><?php echo esc_html( $meta['audio'][$key] ); ?></strong>
2964 if ( $media_dims ) : ?>
2965 <div class="misc-pub-section misc-pub-dimensions">
2966 <?php _e( 'Dimensions:' ); ?> <strong><?php echo $media_dims; ?></strong>
2973 * Parse ID3v2, ID3v1, and getID3 comments to extract usable data
2977 * @param array $metadata An existing array with data
2978 * @param array $data Data supplied by ID3 tags
2980 function wp_add_id3_tag_data( &$metadata, $data ) {
2981 foreach ( array( 'id3v2', 'id3v1' ) as $version ) {
2982 if ( ! empty( $data[$version]['comments'] ) ) {
2983 foreach ( $data[$version]['comments'] as $key => $list ) {
2984 if ( 'length' !== $key && ! empty( $list ) ) {
2985 $metadata[$key] = reset( $list );
2986 // Fix bug in byte stream analysis.
2987 if ( 'terms_of_use' === $key && 0 === strpos( $metadata[$key], 'yright notice.' ) )
2988 $metadata[$key] = 'Cop' . $metadata[$key];
2995 if ( ! empty( $data['id3v2']['APIC'] ) ) {
2996 $image = reset( $data['id3v2']['APIC']);
2997 if ( ! empty( $image['data'] ) ) {
2998 $metadata['image'] = array(
2999 'data' => $image['data'],
3000 'mime' => $image['image_mime'],
3001 'width' => $image['image_width'],
3002 'height' => $image['image_height']
3005 } elseif ( ! empty( $data['comments']['picture'] ) ) {
3006 $image = reset( $data['comments']['picture'] );
3007 if ( ! empty( $image['data'] ) ) {
3008 $metadata['image'] = array(
3009 'data' => $image['data'],
3010 'mime' => $image['image_mime']
3017 * Retrieve metadata from a video file's ID3 tags
3021 * @param string $file Path to file.
3022 * @return array|bool Returns array of metadata, if found.
3024 function wp_read_video_metadata( $file ) {
3025 if ( ! file_exists( $file ) ) {
3029 $metadata = array();
3031 if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
3032 define( 'GETID3_TEMP_DIR', get_temp_dir() );
3035 if ( ! class_exists( 'getID3', false ) ) {
3036 require( ABSPATH . WPINC . '/ID3/getid3.php' );
3038 $id3 = new getID3();
3039 $data = $id3->analyze( $file );
3041 if ( isset( $data['video']['lossless'] ) )
3042 $metadata['lossless'] = $data['video']['lossless'];
3043 if ( ! empty( $data['video']['bitrate'] ) )
3044 $metadata['bitrate'] = (int) $data['video']['bitrate'];
3045 if ( ! empty( $data['video']['bitrate_mode'] ) )
3046 $metadata['bitrate_mode'] = $data['video']['bitrate_mode'];
3047 if ( ! empty( $data['filesize'] ) )
3048 $metadata['filesize'] = (int) $data['filesize'];
3049 if ( ! empty( $data['mime_type'] ) )
3050 $metadata['mime_type'] = $data['mime_type'];
3051 if ( ! empty( $data['playtime_seconds'] ) )
3052 $metadata['length'] = (int) round( $data['playtime_seconds'] );
3053 if ( ! empty( $data['playtime_string'] ) )
3054 $metadata['length_formatted'] = $data['playtime_string'];
3055 if ( ! empty( $data['video']['resolution_x'] ) )
3056 $metadata['width'] = (int) $data['video']['resolution_x'];
3057 if ( ! empty( $data['video']['resolution_y'] ) )
3058 $metadata['height'] = (int) $data['video']['resolution_y'];
3059 if ( ! empty( $data['fileformat'] ) )
3060 $metadata['fileformat'] = $data['fileformat'];
3061 if ( ! empty( $data['video']['dataformat'] ) )
3062 $metadata['dataformat'] = $data['video']['dataformat'];
3063 if ( ! empty( $data['video']['encoder'] ) )
3064 $metadata['encoder'] = $data['video']['encoder'];
3065 if ( ! empty( $data['video']['codec'] ) )
3066 $metadata['codec'] = $data['video']['codec'];
3068 if ( ! empty( $data['audio'] ) ) {
3069 unset( $data['audio']['streams'] );
3070 $metadata['audio'] = $data['audio'];
3073 wp_add_id3_tag_data( $metadata, $data );
3079 * Retrieve metadata from a audio file's ID3 tags
3083 * @param string $file Path to file.
3084 * @return array|bool Returns array of metadata, if found.
3086 function wp_read_audio_metadata( $file ) {
3087 if ( ! file_exists( $file ) ) {
3090 $metadata = array();
3092 if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
3093 define( 'GETID3_TEMP_DIR', get_temp_dir() );
3096 if ( ! class_exists( 'getID3', false ) ) {
3097 require( ABSPATH . WPINC . '/ID3/getid3.php' );
3099 $id3 = new getID3();
3100 $data = $id3->analyze( $file );
3102 if ( ! empty( $data['audio'] ) ) {
3103 unset( $data['audio']['streams'] );
3104 $metadata = $data['audio'];
3107 if ( ! empty( $data['fileformat'] ) )
3108 $metadata['fileformat'] = $data['fileformat'];
3109 if ( ! empty( $data['filesize'] ) )
3110 $metadata['filesize'] = (int) $data['filesize'];
3111 if ( ! empty( $data['mime_type'] ) )
3112 $metadata['mime_type'] = $data['mime_type'];
3113 if ( ! empty( $data['playtime_seconds'] ) )
3114 $metadata['length'] = (int) round( $data['playtime_seconds'] );
3115 if ( ! empty( $data['playtime_string'] ) )
3116 $metadata['length_formatted'] = $data['playtime_string'];
3118 wp_add_id3_tag_data( $metadata, $data );
3124 * Encapsulate logic for Attach/Detach actions
3128 * @global wpdb $wpdb WordPress database abstraction object.
3130 * @param int $parent_id Attachment parent ID.
3131 * @param string $action Optional. Attach/detach action. Accepts 'attach' or 'detach'.
3134 function wp_media_attach_action( $parent_id, $action = 'attach' ) {
3137 if ( ! $parent_id ) {
3141 if ( ! current_user_can( 'edit_post', $parent_id ) ) {
3142 wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
3145 foreach ( (array) $_REQUEST['media'] as $att_id ) {
3146 $att_id = (int) $att_id;
3148 if ( ! current_user_can( 'edit_post', $att_id ) ) {
3155 if ( ! empty( $ids ) ) {
3156 $ids_string = implode( ',', $ids );
3157 if ( 'attach' === $action ) {
3158 $result = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $ids_string )", $parent_id ) );
3160 $result = $wpdb->query( "UPDATE $wpdb->posts SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( $ids_string )" );
3163 foreach ( $ids as $att_id ) {
3164 clean_attachment_cache( $att_id );
3168 if ( isset( $result ) ) {
3169 $location = 'upload.php';
3170 if ( $referer = wp_get_referer() ) {
3171 if ( false !== strpos( $referer, 'upload.php' ) ) {
3172 $location = remove_query_arg( array( 'attached', 'detach' ), $referer );
3176 $key = 'attach' === $action ? 'attached' : 'detach';
3177 $location = add_query_arg( array( $key => $result ), $location );
3178 wp_redirect( $location );