3 * WordPress API for media display.
10 * Scale down the default size of an image.
12 * This is so that the image is a better fit for the editor and theme.
14 * The `$size` parameter accepts either an array or a string. The supported string
15 * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
16 * 128 width and 96 height in pixels. Also supported for the string value is
17 * 'medium', 'medium_large' and 'full'. The 'full' isn't actually supported, but any value other
18 * than the supported will result in the content_width size or 500 if that is
21 * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
22 * called on the calculated array for width and height, respectively. The second
23 * parameter will be the value that was in the $size parameter. The returned
24 * type for the hook is an array with the width as the first element and the
25 * height as the second element.
29 * @global int $content_width
30 * @global array $_wp_additional_image_sizes
32 * @param int $width Width of the image in pixels.
33 * @param int $height Height of the image in pixels.
34 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array
35 * of width and height values in pixels (in that order).
37 * @param string $context Optional. Could be 'display' (like in a theme) or 'edit'
38 * (like inserting into an editor). Default null.
39 * @return array Width and height of what the result image should resize to.
41 function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
42 global $content_width, $_wp_additional_image_sizes;
45 $context = is_admin() ? 'edit' : 'display';
47 if ( is_array($size) ) {
48 $max_width = $size[0];
49 $max_height = $size[1];
51 elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
52 $max_width = intval(get_option('thumbnail_size_w'));
53 $max_height = intval(get_option('thumbnail_size_h'));
54 // last chance thumbnail size defaults
55 if ( !$max_width && !$max_height ) {
60 elseif ( $size == 'medium' ) {
61 $max_width = intval(get_option('medium_size_w'));
62 $max_height = intval(get_option('medium_size_h'));
65 elseif ( $size == 'medium_large' ) {
66 $max_width = intval( get_option( 'medium_large_size_w' ) );
67 $max_height = intval( get_option( 'medium_large_size_h' ) );
69 if ( intval( $content_width ) > 0 ) {
70 $max_width = min( intval( $content_width ), $max_width );
73 elseif ( $size == 'large' ) {
75 * We're inserting a large size image into the editor. If it's a really
76 * big image we'll scale it down to fit reasonably within the editor
77 * itself, and within the theme's content width if it's known. The user
78 * can resize it in the editor if they wish.
80 $max_width = intval(get_option('large_size_w'));
81 $max_height = intval(get_option('large_size_h'));
82 if ( intval($content_width) > 0 ) {
83 $max_width = min( intval($content_width), $max_width );
85 } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
86 $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
87 $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
88 if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
89 $max_width = min( intval($content_width), $max_width );
91 // $size == 'full' has no constraint
94 $max_height = $height;
98 * Filter the maximum image size dimensions for the editor.
102 * @param array $max_image_size An array with the width as the first element,
103 * and the height as the second element.
104 * @param string|array $size Size of what the result image should be.
105 * @param string $context The context the image is being resized for.
106 * Possible values are 'display' (like in a theme)
107 * or 'edit' (like inserting into an editor).
109 list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
111 return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
115 * Retrieve width and height attributes using given width and height values.
117 * Both attributes are required in the sense that both parameters must have a
118 * value, but are optional in that if you set them to false or null, then they
119 * will not be added to the returned string.
121 * You can set the value using a string, but it will only take numeric values.
122 * If you wish to put 'px' after the numbers, then it will be stripped out of
127 * @param int|string $width Image width in pixels.
128 * @param int|string $height Image height in pixels.
129 * @return string HTML attributes for width and, or height.
131 function image_hwstring( $width, $height ) {
134 $out .= 'width="'.intval($width).'" ';
136 $out .= 'height="'.intval($height).'" ';
141 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
143 * Array with image url, width, height, and whether is intermediate size, in
144 * that order is returned on success is returned. $is_intermediate is true if
145 * $url is a resized image, false if it is the original.
147 * The URL might be the original image, or it might be a resized version. This
148 * function won't create a new resized copy, it will just return an already
149 * resized one if it exists.
151 * A plugin may use the 'image_downsize' filter to hook into and offer image
152 * resizing services for images. The hook must return an array with the same
153 * elements that are returned in the function. The first element being the URL
154 * to the new image that was resized.
158 * @param int $id Attachment ID for image.
159 * @param array|string $size Optional. Image size to scale to. Accepts any valid image size,
160 * or an array of width and height values in pixels (in that order).
162 * @return false|array Array containing the image URL, width, height, and boolean for whether
163 * the image is an intermediate size. False on failure.
165 function image_downsize( $id, $size = 'medium' ) {
167 if ( !wp_attachment_is_image($id) )
171 * Filter whether to preempt the output of image_downsize().
173 * Passing a truthy value to the filter will effectively short-circuit
174 * down-sizing the image, returning that value as output instead.
178 * @param bool $downsize Whether to short-circuit the image downsize. Default false.
179 * @param int $id Attachment ID for image.
180 * @param array|string $size Size of image. Image size or array of width and height values (in that order).
183 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
187 $img_url = wp_get_attachment_url($id);
188 $meta = wp_get_attachment_metadata($id);
189 $width = $height = 0;
190 $is_intermediate = false;
191 $img_url_basename = wp_basename($img_url);
193 // try for a new style intermediate size
194 if ( $intermediate = image_get_intermediate_size($id, $size) ) {
195 $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
196 $width = $intermediate['width'];
197 $height = $intermediate['height'];
198 $is_intermediate = true;
200 elseif ( $size == 'thumbnail' ) {
201 // fall back to the old thumbnail
202 if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
203 $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
206 $is_intermediate = true;
209 if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
210 // any other type: use the real image
211 $width = $meta['width'];
212 $height = $meta['height'];
216 // we have the actual image size, but might need to further constrain it if content_width is narrower
217 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
219 return array( $img_url, $width, $height, $is_intermediate );
226 * Register a new image size.
228 * Cropping behavior for the image size is dependent on the value of $crop:
229 * 1. If false (default), images will be scaled, not cropped.
230 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
231 * - x_crop_position accepts 'left' 'center', or 'right'.
232 * - y_crop_position accepts 'top', 'center', or 'bottom'.
233 * Images will be cropped to the specified dimensions within the defined crop area.
234 * 3. If true, images will be cropped to the specified dimensions using center positions.
238 * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
240 * @param string $name Image size identifier.
241 * @param int $width Image width in pixels.
242 * @param int $height Image height in pixels.
243 * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
244 * An array can specify positioning of the crop area. Default false.
246 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
247 global $_wp_additional_image_sizes;
249 $_wp_additional_image_sizes[ $name ] = array(
250 'width' => absint( $width ),
251 'height' => absint( $height ),
257 * Check if an image size exists.
261 * @global array $_wp_additional_image_sizes
263 * @param string $name The image size to check.
264 * @return bool True if the image size exists, false if not.
266 function has_image_size( $name ) {
267 global $_wp_additional_image_sizes;
269 return isset( $_wp_additional_image_sizes[ $name ] );
273 * Remove a new image size.
277 * @global array $_wp_additional_image_sizes
279 * @param string $name The image size to remove.
280 * @return bool True if the image size was successfully removed, false on failure.
282 function remove_image_size( $name ) {
283 global $_wp_additional_image_sizes;
285 if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
286 unset( $_wp_additional_image_sizes[ $name ] );
294 * Registers an image size for the post thumbnail.
298 * @see add_image_size() for details on cropping behavior.
300 * @param int $width Image width in pixels.
301 * @param int $height Image height in pixels.
302 * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
303 * An array can specify positioning of the crop area. Default false.
305 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
306 add_image_size( 'post-thumbnail', $width, $height, $crop );
310 * Gets an img tag for an image attachment, scaling it down if requested.
312 * The filter 'get_image_tag_class' allows for changing the class name for the
313 * image without having to use regular expressions on the HTML content. The
314 * parameters are: what WordPress will use for the class, the Attachment ID,
315 * image align value, and the size the image should be.
317 * The second filter 'get_image_tag' has the HTML content, which can then be
318 * further manipulated by a plugin to change all attribute values and even HTML
323 * @param int $id Attachment ID.
324 * @param string $alt Image Description for the alt attribute.
325 * @param string $title Image Description for the title attribute.
326 * @param string $align Part of the class name for aligning the image.
327 * @param string|array $size Optional. Registered image size to retrieve a tag for. Accepts any
328 * valid image size, or an array of width and height values in pixels
329 * (in that order). Default 'medium'.
330 * @return string HTML IMG element for given image attachment
332 function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
334 list( $img_src, $width, $height ) = image_downsize($id, $size);
335 $hwstring = image_hwstring($width, $height);
337 $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
339 $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
342 * Filter the value of the attachment's image tag class attribute.
346 * @param string $class CSS class name or space-separated list of classes.
347 * @param int $id Attachment ID.
348 * @param string $align Part of the class name for aligning the image.
349 * @param string|array $size Size of image. Image size or array of width and height values (in that order).
352 $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
354 $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
357 * Filter the HTML content for the image tag.
361 * @param string $html HTML content for the image.
362 * @param int $id Attachment ID.
363 * @param string $alt Alternate text.
364 * @param string $title Attachment title.
365 * @param string $align Part of the class name for aligning the image.
366 * @param string|array $size Size of image. Image size or array of width and height values (in that order).
369 return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
373 * Calculates the new dimensions for a down-sampled image.
375 * If either width or height are empty, no constraint is applied on
380 * @param int $current_width Current width of the image.
381 * @param int $current_height Current height of the image.
382 * @param int $max_width Optional. Max width in pixels to constrain to. Default 0.
383 * @param int $max_height Optional. Max height in pixels to constrain to. Default 0.
384 * @return array First item is the width, the second item is the height.
386 function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
387 if ( !$max_width && !$max_height )
388 return array( $current_width, $current_height );
390 $width_ratio = $height_ratio = 1.0;
391 $did_width = $did_height = false;
393 if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
394 $width_ratio = $max_width / $current_width;
398 if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
399 $height_ratio = $max_height / $current_height;
403 // Calculate the larger/smaller ratios
404 $smaller_ratio = min( $width_ratio, $height_ratio );
405 $larger_ratio = max( $width_ratio, $height_ratio );
407 if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
408 // The larger ratio is too big. It would result in an overflow.
409 $ratio = $smaller_ratio;
411 // The larger ratio fits, and is likely to be a more "snug" fit.
412 $ratio = $larger_ratio;
415 // Very small dimensions may result in 0, 1 should be the minimum.
416 $w = max ( 1, (int) round( $current_width * $ratio ) );
417 $h = max ( 1, (int) round( $current_height * $ratio ) );
419 // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
420 // We also have issues with recursive calls resulting in an ever-changing result. Constraining to the result of a constraint should yield the original result.
421 // Thus we look for dimensions that are one pixel shy of the max value and bump them up
423 // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
424 if ( $did_width && $w == $max_width - 1 ) {
425 $w = $max_width; // Round it up
428 // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
429 if ( $did_height && $h == $max_height - 1 ) {
430 $h = $max_height; // Round it up
434 * Filter dimensions to constrain down-sampled images to.
438 * @param array $dimensions The image width and height.
439 * @param int $current_width The current width of the image.
440 * @param int $current_height The current height of the image.
441 * @param int $max_width The maximum width permitted.
442 * @param int $max_height The maximum height permitted.
444 return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
448 * Retrieves calculated resize dimensions for use in WP_Image_Editor.
450 * Calculates dimensions and coordinates for a resized image that fits
451 * within a specified width and height.
453 * Cropping behavior is dependent on the value of $crop:
454 * 1. If false (default), images will not be cropped.
455 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
456 * - x_crop_position accepts 'left' 'center', or 'right'.
457 * - y_crop_position accepts 'top', 'center', or 'bottom'.
458 * Images will be cropped to the specified dimensions within the defined crop area.
459 * 3. If true, images will be cropped to the specified dimensions using center positions.
463 * @param int $orig_w Original width in pixels.
464 * @param int $orig_h Original height in pixels.
465 * @param int $dest_w New width in pixels.
466 * @param int $dest_h New height in pixels.
467 * @param bool|array $crop Optional. Whether to crop image to specified width and height or resize.
468 * An array can specify positioning of the crop area. Default false.
469 * @return false|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
471 function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
473 if ($orig_w <= 0 || $orig_h <= 0)
475 // at least one of dest_w or dest_h must be specific
476 if ($dest_w <= 0 && $dest_h <= 0)
480 * Filter whether to preempt calculating the image resize dimensions.
482 * Passing a non-null value to the filter will effectively short-circuit
483 * image_resize_dimensions(), returning that value instead.
487 * @param null|mixed $null Whether to preempt output of the resize dimensions.
488 * @param int $orig_w Original width in pixels.
489 * @param int $orig_h Original height in pixels.
490 * @param int $dest_w New width in pixels.
491 * @param int $dest_h New height in pixels.
492 * @param bool|array $crop Whether to crop image to specified width and height or resize.
493 * An array can specify positioning of the crop area. Default false.
495 $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
496 if ( null !== $output )
500 // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
501 $aspect_ratio = $orig_w / $orig_h;
502 $new_w = min($dest_w, $orig_w);
503 $new_h = min($dest_h, $orig_h);
506 $new_w = (int) round( $new_h * $aspect_ratio );
510 $new_h = (int) round( $new_w / $aspect_ratio );
513 $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
515 $crop_w = round($new_w / $size_ratio);
516 $crop_h = round($new_h / $size_ratio);
518 if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
519 $crop = array( 'center', 'center' );
522 list( $x, $y ) = $crop;
524 if ( 'left' === $x ) {
526 } elseif ( 'right' === $x ) {
527 $s_x = $orig_w - $crop_w;
529 $s_x = floor( ( $orig_w - $crop_w ) / 2 );
532 if ( 'top' === $y ) {
534 } elseif ( 'bottom' === $y ) {
535 $s_y = $orig_h - $crop_h;
537 $s_y = floor( ( $orig_h - $crop_h ) / 2 );
540 // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
547 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
550 // if the resulting image would be the same size or larger we don't want to resize it
551 if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
555 // the return array matches the parameters to imagecopyresampled()
556 // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
557 return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
562 * Resizes an image to make a thumbnail or intermediate size.
564 * The returned array has the file size, the image width, and image height. The
565 * filter 'image_make_intermediate_size' can be used to hook in and change the
566 * values of the returned array. The only parameter is the resized file path.
570 * @param string $file File path.
571 * @param int $width Image width.
572 * @param int $height Image height.
573 * @param bool $crop Optional. Whether to crop image to specified width and height or resize.
575 * @return false|array False, if no image was created. Metadata array on success.
577 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
578 if ( $width || $height ) {
579 $editor = wp_get_image_editor( $file );
581 if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
584 $resized_file = $editor->save();
586 if ( ! is_wp_error( $resized_file ) && $resized_file ) {
587 unset( $resized_file['path'] );
588 return $resized_file;
595 * Retrieves the image's intermediate size (resized) path, width, and height.
597 * The $size parameter can be an array with the width and height respectively.
598 * If the size matches the 'sizes' metadata array for width and height, then it
599 * will be used. If there is no direct match, then the nearest image size larger
600 * than the specified size will be used. If nothing is found, then the function
601 * will break out and return false.
603 * The metadata 'sizes' is used for compatible sizes that can be used for the
604 * parameter $size value.
606 * The url path will be given, when the $size parameter is a string.
608 * If you are passing an array for the $size, you should consider using
609 * add_image_size() so that a cropped version is generated. It's much more
610 * efficient than having to find the closest-sized image and then having the
611 * browser scale down the image.
615 * @param int $post_id Attachment ID.
616 * @param array|string $size Optional. Image size. Accepts any valid image size, or an array
617 * of width and height values in pixels (in that order).
618 * Default 'thumbnail'.
619 * @return false|array $data {
620 * Array of file relative path, width, and height on success. Additionally includes absolute
621 * path and URL if registered size is passed to $size parameter. False on failure.
623 * @type string $file Image's path relative to uploads directory
624 * @type int $width Width of image
625 * @type int $height Height of image
626 * @type string $path Optional. Image's absolute filesystem path. Only returned if registered
627 * size is passed to `$size` parameter.
628 * @type string $url Optional. Image's URL. Only returned if registered size is passed to `$size`
632 function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
633 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
636 // get the best one for a specified set of dimensions
637 if ( is_array($size) && !empty($imagedata['sizes']) ) {
638 $candidates = array();
640 foreach ( $imagedata['sizes'] as $_size => $data ) {
641 // If there's an exact match to an existing image size, short circuit.
642 if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
643 list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
645 /** This filter is documented in wp-includes/media.php */
646 return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
648 // If it's not an exact match but it's at least the dimensions requested.
649 if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
650 $candidates[ $data['width'] * $data['height'] ] = $_size;
654 if ( ! empty( $candidates ) ) {
655 // find for the smallest image not smaller than the desired size
656 ksort( $candidates );
657 foreach ( $candidates as $_size ) {
658 $data = $imagedata['sizes'][$_size];
660 // Skip images with unexpectedly divergent aspect ratios (crops)
661 // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
662 $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
663 // If the size doesn't match within one pixel, then it is of a different aspect ratio, so we skip it, unless it's the thumbnail size
664 if ( 'thumbnail' != $_size &&
666 || ( $maybe_cropped[4] != $data['width'] && $maybe_cropped[4] + 1 != $data['width'] )
667 || ( $maybe_cropped[5] != $data['height'] && $maybe_cropped[5] + 1 != $data['height'] )
671 // If we're still here, then we're going to use this size.
672 list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
674 /** This filter is documented in wp-includes/media.php */
675 return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
680 if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
683 $data = $imagedata['sizes'][$size];
684 // include the full filesystem path of the intermediate file
685 if ( empty($data['path']) && !empty($data['file']) ) {
686 $file_url = wp_get_attachment_url($post_id);
687 $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
688 $data['url'] = path_join( dirname($file_url), $data['file'] );
692 * Filter the output of image_get_intermediate_size()
696 * @see image_get_intermediate_size()
698 * @param array $data Array of file relative path, width, and height on success. May also include
699 * file absolute path and URL.
700 * @param int $post_id The post_id of the image attachment
701 * @param string|array $size Registered image size or flat array of initially-requested height and width
702 * dimensions (in that order).
704 return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
708 * Gets the available intermediate image sizes.
712 * @global array $_wp_additional_image_sizes
714 * @return array Returns a filtered array of image size strings.
716 function get_intermediate_image_sizes() {
717 global $_wp_additional_image_sizes;
718 $image_sizes = array('thumbnail', 'medium', 'medium_large', 'large'); // Standard sizes
719 if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
720 $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
723 * Filter the list of intermediate image sizes.
727 * @param array $image_sizes An array of intermediate image sizes. Defaults
728 * are 'thumbnail', 'medium', 'medium_large', 'large'.
730 return apply_filters( 'intermediate_image_sizes', $image_sizes );
734 * Retrieve an image to represent an attachment.
736 * A mime icon for files, thumbnail or intermediate size for images.
738 * The returned array contains four values: the URL of the attachment image src,
739 * the width of the image file, the height of the image file, and a boolean
740 * representing whether the returned array describes an intermediate (generated)
741 * image size or the original, full-sized upload.
745 * @param int $attachment_id Image attachment ID.
746 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
747 * and height values in pixels (in that order). Default 'thumbnail'.
748 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
749 * @return false|array Returns an array (url, width, height, is_intermediate), or false, if no image is available.
751 function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
752 // get a thumbnail or intermediate image if there is one
753 $image = image_downsize( $attachment_id, $size );
757 if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {
758 /** This filter is documented in wp-includes/post.php */
759 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
761 $src_file = $icon_dir . '/' . wp_basename( $src );
762 @list( $width, $height ) = getimagesize( $src_file );
765 if ( $src && $width && $height ) {
766 $image = array( $src, $width, $height );
770 * Filter the image src result.
774 * @param array|false $image Either array with src, width & height, icon src, or false.
775 * @param int $attachment_id Image attachment ID.
776 * @param string|array $size Size of image. Image size or array of width and height values
777 * (in that order). Default 'thumbnail'.
778 * @param bool $icon Whether the image should be treated as an icon. Default false.
780 return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
784 * Get an HTML img element representing an image attachment
786 * While `$size` will accept an array, it is better to register a size with
787 * add_image_size() so that a cropped version is generated. It's much more
788 * efficient than having to find the closest-sized image and then having the
789 * browser scale down the image.
793 * @param int $attachment_id Image attachment ID.
794 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
795 * and height values in pixels (in that order). Default 'thumbnail'.
796 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
797 * @param string|array $attr Optional. Attributes for the image markup. Default empty.
798 * @return string HTML img element or empty string on failure.
800 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
802 $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
804 list($src, $width, $height) = $image;
805 $hwstring = image_hwstring($width, $height);
807 if ( is_array( $size_class ) ) {
808 $size_class = join( 'x', $size_class );
810 $attachment = get_post($attachment_id);
811 $default_attr = array(
813 'class' => "attachment-$size_class size-$size_class",
814 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
816 if ( empty($default_attr['alt']) )
817 $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
818 if ( empty($default_attr['alt']) )
819 $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
821 $attr = wp_parse_args( $attr, $default_attr );
823 // Generate 'srcset' and 'sizes' if not already present.
824 if ( empty( $attr['srcset'] ) ) {
825 $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
827 if ( is_array( $image_meta ) ) {
828 $size_array = array( absint( $width ), absint( $height ) );
829 $srcset = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
830 $sizes = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
832 if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
833 $attr['srcset'] = $srcset;
835 if ( empty( $attr['sizes'] ) ) {
836 $attr['sizes'] = $sizes;
843 * Filter the list of attachment image attributes.
847 * @param array $attr Attributes for the image markup.
848 * @param WP_Post $attachment Image attachment post.
849 * @param string|array $size Requested size. Image size or array of width and height values
850 * (in that order). Default 'thumbnail'.
852 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
853 $attr = array_map( 'esc_attr', $attr );
854 $html = rtrim("<img $hwstring");
855 foreach ( $attr as $name => $value ) {
856 $html .= " $name=" . '"' . $value . '"';
865 * Get the URL of an image attachment.
869 * @param int $attachment_id Image attachment ID.
870 * @param string|array $size Optional. Image size to retrieve. Accepts any valid image size, or an array
871 * of width and height values in pixels (in that order). Default 'thumbnail'.
872 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
873 * @return string|false Attachment URL or false if no image is available.
875 function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
876 $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
877 return isset( $image['0'] ) ? $image['0'] : false;
881 * Get the attachment path relative to the upload directory.
886 * @param string $file Attachment file name.
887 * @return string Attachment path relative to the upload directory.
889 function _wp_get_attachment_relative_path( $file ) {
890 $dirname = dirname( $file );
892 if ( '.' === $dirname ) {
896 if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
897 // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads)
898 $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
899 $dirname = ltrim( $dirname, '/' );
906 * Caches and returns the base URL of the uploads directory.
911 * @return string The base URL, cached.
913 function _wp_upload_dir_baseurl() {
914 static $baseurl = array();
916 $blog_id = get_current_blog_id();
918 if ( empty( $baseurl[$blog_id] ) ) {
919 $uploads_dir = wp_upload_dir();
920 $baseurl[$blog_id] = $uploads_dir['baseurl'];
923 return $baseurl[$blog_id];
927 * Get the image size as array from its meta data.
929 * Used for responsive images.
934 * @param string $size_name Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
935 * @param array $image_meta The image meta data.
936 * @return array|bool Array of width and height values in pixels (in that order)
937 * or false if the size doesn't exist.
939 function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
940 if ( $size_name === 'full' ) {
942 absint( $image_meta['width'] ),
943 absint( $image_meta['height'] ),
945 } elseif ( ! empty( $image_meta['sizes'][$size_name] ) ) {
947 absint( $image_meta['sizes'][$size_name]['width'] ),
948 absint( $image_meta['sizes'][$size_name]['height'] ),
956 * Retrieves the value for an image attachment's 'srcset' attribute.
960 * @see wp_calculate_image_srcset()
962 * @param int $attachment_id Image attachment ID.
963 * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of
964 * width and height values in pixels (in that order). Default 'medium'.
965 * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
967 * @return string|bool A 'srcset' value string or false.
969 function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
970 if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
974 if ( ! is_array( $image_meta ) ) {
975 $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
978 $image_src = $image[0];
984 return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
988 * A helper function to calculate the image sources to include in a 'srcset' attribute.
992 * @param array $size_array Array of width and height values in pixels (in that order).
993 * @param string $image_src The 'src' of the image.
994 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
995 * @param int $attachment_id Optional. The image attachment ID to pass to the filter. Default 0.
996 * @return string|bool The 'srcset' attribute value. False on error or when only one source exists.
998 function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
1000 * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
1002 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
1003 * @param array $size_array Array of width and height values in pixels (in that order).
1004 * @param string $image_src The 'src' of the image.
1005 * @param int $attachment_id The image attachment ID or 0 if not supplied.
1007 $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
1009 if ( empty( $image_meta['sizes'] ) ) {
1013 $image_sizes = $image_meta['sizes'];
1015 // Get the width and height of the image.
1016 $image_width = (int) $size_array[0];
1017 $image_height = (int) $size_array[1];
1019 // Bail early if error/no width.
1020 if ( $image_width < 1 ) {
1024 $image_basename = wp_basename( $image_meta['file'] );
1027 * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
1028 * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
1029 * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
1031 if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
1032 $image_sizes['full'] = array(
1033 'width' => $image_meta['width'],
1034 'height' => $image_meta['height'],
1035 'file' => $image_basename,
1037 } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
1041 // Retrieve the uploads sub-directory from the full size image.
1042 $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1045 $dirname = trailingslashit( $dirname );
1048 $image_baseurl = _wp_upload_dir_baseurl();
1049 $image_baseurl = trailingslashit( $image_baseurl ) . $dirname;
1051 // Calculate the image aspect ratio.
1052 $image_ratio = $image_height / $image_width;
1055 * Images that have been edited in WordPress after being uploaded will
1056 * contain a unique hash. Look for that hash and use it later to filter
1057 * out images that are leftovers from previous versions.
1059 $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
1062 * Filter the maximum image width to be included in a 'srcset' attribute.
1066 * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.
1067 * @param array $size_array Array of width and height values in pixels (in that order).
1069 $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
1071 // Array to hold URL candidates.
1075 * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
1076 * meta match our $image_src. If no mathces are found we don't return a srcset to avoid serving
1077 * an incorrect image. See #35045.
1079 $src_matched = false;
1082 * Loop through available images. Only use images that are resized
1083 * versions of the same edit.
1085 foreach ( $image_sizes as $image ) {
1087 // If the file name is part of the `src`, we've confirmed a match.
1088 if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
1089 $src_matched = true;
1092 // Filter out images that are from previous edits.
1093 if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
1098 * Filter out images that are wider than '$max_srcset_image_width' unless
1099 * that file is in the 'src' attribute.
1101 if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width &&
1102 false === strpos( $image_src, $image['file'] ) ) {
1107 // Calculate the new image ratio.
1108 if ( $image['width'] ) {
1109 $image_ratio_compare = $image['height'] / $image['width'];
1111 $image_ratio_compare = 0;
1114 // If the new ratio differs by less than 0.002, use it.
1115 if ( abs( $image_ratio - $image_ratio_compare ) < 0.002 ) {
1116 // Add the URL, descriptor, and value to the sources array to be returned.
1117 $sources[ $image['width'] ] = array(
1118 'url' => $image_baseurl . $image['file'],
1119 'descriptor' => 'w',
1120 'value' => $image['width'],
1126 * Filter an image's 'srcset' sources.
1130 * @param array $sources {
1131 * One or more arrays of source data to include in the 'srcset'.
1133 * @type array $width {
1134 * @type string $url The URL of an image source.
1135 * @type string $descriptor The descriptor type used in the image candidate string,
1136 * either 'w' or 'x'.
1137 * @type int $value The source width if paired with a 'w' descriptor, or a
1138 * pixel density value if paired with an 'x' descriptor.
1141 * @param array $size_array Array of width and height values in pixels (in that order).
1142 * @param string $image_src The 'src' of the image.
1143 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
1144 * @param int $attachment_id Image attachment ID or 0.
1146 $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
1148 // Only return a 'srcset' value if there is more than one source.
1149 if ( ! $src_matched || count( $sources ) < 2 ) {
1155 foreach ( $sources as $source ) {
1156 $srcset .= $source['url'] . ' ' . $source['value'] . $source['descriptor'] . ', ';
1159 return rtrim( $srcset, ', ' );
1163 * Retrieves the value for an image attachment's 'sizes' attribute.
1167 * @see wp_calculate_image_sizes()
1169 * @param int $attachment_id Image attachment ID.
1170 * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of width
1171 * and height values in pixels (in that order). Default 'medium'.
1172 * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1174 * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
1176 function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
1177 if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
1181 if ( ! is_array( $image_meta ) ) {
1182 $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
1185 $image_src = $image[0];
1186 $size_array = array(
1187 absint( $image[1] ),
1191 return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1195 * Creates a 'sizes' attribute value for an image.
1199 * @param array|string $size Image size to retrieve. Accepts any valid image size, or an array
1200 * of width and height values in pixels (in that order). Default 'medium'.
1201 * @param string $image_src Optional. The URL to the image file. Default null.
1202 * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1204 * @param int $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
1205 * is needed when using the image size name as argument for `$size`. Default 0.
1206 * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
1208 function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
1211 if ( is_array( $size ) ) {
1212 $width = absint( $size[0] );
1213 } elseif ( is_string( $size ) ) {
1214 if ( ! $image_meta && $attachment_id ) {
1215 $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
1218 if ( is_array( $image_meta ) ) {
1219 $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
1220 if ( $size_array ) {
1221 $width = absint( $size_array[0] );
1230 // Setup the default 'sizes' attribute.
1231 $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
1234 * Filter the output of 'wp_calculate_image_sizes()'.
1238 * @param string $sizes A source size value for use in a 'sizes' attribute.
1239 * @param array|string $size Requested size. Image size or array of width and height values
1240 * in pixels (in that order).
1241 * @param string|null $image_src The URL to the image file or null.
1242 * @param array|null $image_meta The image meta data as returned by wp_get_attachment_metadata() or null.
1243 * @param int $attachment_id Image attachment ID of the original image or 0.
1245 return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
1249 * Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
1253 * @see wp_image_add_srcset_and_sizes()
1255 * @param string $content The raw post content to be filtered.
1256 * @return string Converted content with 'srcset' and 'sizes' attributes added to images.
1258 function wp_make_content_images_responsive( $content ) {
1259 if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
1263 $selected_images = $attachment_ids = array();
1265 foreach( $matches[0] as $image ) {
1266 if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) &&
1267 ( $attachment_id = absint( $class_id[1] ) ) ) {
1270 * If exactly the same image tag is used more than once, overwrite it.
1271 * All identical tags will be replaced later with 'str_replace()'.
1273 $selected_images[ $image ] = $attachment_id;
1274 // Overwrite the ID when the same image is included more than once.
1275 $attachment_ids[ $attachment_id ] = true;
1279 if ( count( $attachment_ids ) > 1 ) {
1281 * Warm object cache for use with 'get_post_meta()'.
1283 * To avoid making a database call for each image, a single query
1284 * warms the object cache with the meta information for all images.
1286 update_meta_cache( 'post', array_keys( $attachment_ids ) );
1289 foreach ( $selected_images as $image => $attachment_id ) {
1290 $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
1291 $content = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content );
1298 * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
1302 * @see wp_calculate_image_srcset()
1303 * @see wp_calculate_image_sizes()
1305 * @param string $image An HTML 'img' element to be filtered.
1306 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
1307 * @param int $attachment_id Image attachment ID.
1308 * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
1310 function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
1311 // Ensure the image meta exists.
1312 if ( empty( $image_meta['sizes'] ) ) {
1316 $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
1317 list( $image_src ) = explode( '?', $image_src );
1319 // Return early if we couldn't get the image source.
1320 if ( ! $image_src ) {
1324 // Bail early if an image has been inserted and later edited.
1325 if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
1326 strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
1331 $width = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
1332 $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
1334 if ( ! $width || ! $height ) {
1336 * If attempts to parse the size value failed, attempt to use the image meta data to match
1337 * the image file name from 'src' against the available sizes for an attachment.
1339 $image_filename = wp_basename( $image_src );
1341 if ( $image_filename === wp_basename( $image_meta['file'] ) ) {
1342 $width = (int) $image_meta['width'];
1343 $height = (int) $image_meta['height'];
1345 foreach( $image_meta['sizes'] as $image_size_data ) {
1346 if ( $image_filename === $image_size_data['file'] ) {
1347 $width = (int) $image_size_data['width'];
1348 $height = (int) $image_size_data['height'];
1355 if ( ! $width || ! $height ) {
1359 $size_array = array( $width, $height );
1360 $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1363 // Check if there is already a 'sizes' attribute.
1364 $sizes = strpos( $image, ' sizes=' );
1367 $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1371 if ( $srcset && $sizes ) {
1372 // Format the 'srcset' and 'sizes' string and escape attributes.
1373 $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
1375 if ( is_string( $sizes ) ) {
1376 $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
1379 // Add 'srcset' and 'sizes' attributes to the image markup.
1380 $image = preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
1387 * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
1389 * Uses the 'begin_fetch_post_thumbnail_html' and 'end_fetch_post_thumbnail_html' action hooks to
1390 * dynamically add/remove itself so as to only filter post thumbnails.
1395 * @param array $attr Thumbnail attributes including src, class, alt, title.
1396 * @return array Modified array of attributes including the new 'wp-post-image' class.
1398 function _wp_post_thumbnail_class_filter( $attr ) {
1399 $attr['class'] .= ' wp-post-image';
1404 * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
1405 * filter hook. Internal use only.
1410 * @param array $attr Thumbnail attributes including src, class, alt, title.
1412 function _wp_post_thumbnail_class_filter_add( $attr ) {
1413 add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
1417 * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
1418 * filter hook. Internal use only.
1423 * @param array $attr Thumbnail attributes including src, class, alt, title.
1425 function _wp_post_thumbnail_class_filter_remove( $attr ) {
1426 remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
1429 add_shortcode('wp_caption', 'img_caption_shortcode');
1430 add_shortcode('caption', 'img_caption_shortcode');
1433 * Builds the Caption shortcode output.
1435 * Allows a plugin to replace the content that would otherwise be returned. The
1436 * filter is 'img_caption_shortcode' and passes an empty string, the attr
1437 * parameter and the content parameter values.
1439 * The supported attributes for the shortcode are 'id', 'align', 'width', and
1444 * @param array $attr {
1445 * Attributes of the caption shortcode.
1447 * @type string $id ID of the div element for the caption.
1448 * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
1449 * 'aligncenter', alignright', 'alignnone'.
1450 * @type int $width The width of the caption, in pixels.
1451 * @type string $caption The caption text.
1452 * @type string $class Additional class name(s) added to the caption container.
1454 * @param string $content Shortcode content.
1455 * @return string HTML content to display the caption.
1457 function img_caption_shortcode( $attr, $content = null ) {
1458 // New-style shortcode with the caption inside the shortcode with the link and image tags.
1459 if ( ! isset( $attr['caption'] ) ) {
1460 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
1461 $content = $matches[1];
1462 $attr['caption'] = trim( $matches[2] );
1464 } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
1465 $attr['caption'] = wp_kses( $attr['caption'], 'post' );
1469 * Filter the default caption shortcode output.
1471 * If the filtered output isn't empty, it will be used instead of generating
1472 * the default caption template.
1476 * @see img_caption_shortcode()
1478 * @param string $output The caption output. Default empty.
1479 * @param array $attr Attributes of the caption shortcode.
1480 * @param string $content The image element, possibly wrapped in a hyperlink.
1482 $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
1483 if ( $output != '' )
1486 $atts = shortcode_atts( array(
1488 'align' => 'alignnone',
1492 ), $attr, 'caption' );
1494 $atts['width'] = (int) $atts['width'];
1495 if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
1498 if ( ! empty( $atts['id'] ) )
1499 $atts['id'] = 'id="' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '" ';
1501 $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
1503 $html5 = current_theme_supports( 'html5', 'caption' );
1504 // HTML5 captions never added the extra 10px to the image width
1505 $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
1508 * Filter the width of an image's caption.
1510 * By default, the caption is 10 pixels greater than the width of the image,
1511 * to prevent post content from running up against a floated image.
1515 * @see img_caption_shortcode()
1517 * @param int $width Width of the caption in pixels. To remove this inline style,
1519 * @param array $atts Attributes of the caption shortcode.
1520 * @param string $content The image element, possibly wrapped in a hyperlink.
1522 $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
1525 if ( $caption_width )
1526 $style = 'style="width: ' . (int) $caption_width . 'px" ';
1530 $html = '<figure ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
1531 . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
1533 $html = '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
1534 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
1540 add_shortcode('gallery', 'gallery_shortcode');
1543 * Builds the Gallery shortcode output.
1545 * This implements the functionality of the Gallery Shortcode for displaying
1546 * WordPress images on a post.
1550 * @staticvar int $instance
1552 * @param array $attr {
1553 * Attributes of the gallery shortcode.
1555 * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
1556 * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
1557 * Accepts any valid SQL ORDERBY statement.
1558 * @type int $id Post ID.
1559 * @type string $itemtag HTML tag to use for each image in the gallery.
1560 * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
1561 * @type string $icontag HTML tag to use for each image's icon.
1562 * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
1563 * @type string $captiontag HTML tag to use for each image's caption.
1564 * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
1565 * @type int $columns Number of columns of images to display. Default 3.
1566 * @type string|array $size Size of the images to display. Accepts any valid image size, or an array of width
1567 * and height values in pixels (in that order). Default 'thumbnail'.
1568 * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
1569 * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
1570 * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
1571 * @type string $link What to link each image to. Default empty (links to the attachment page).
1572 * Accepts 'file', 'none'.
1574 * @return string HTML content to display gallery.
1576 function gallery_shortcode( $attr ) {
1579 static $instance = 0;
1582 if ( ! empty( $attr['ids'] ) ) {
1583 // 'ids' is explicitly ordered, unless you specify otherwise.
1584 if ( empty( $attr['orderby'] ) ) {
1585 $attr['orderby'] = 'post__in';
1587 $attr['include'] = $attr['ids'];
1591 * Filter the default gallery shortcode output.
1593 * If the filtered output isn't empty, it will be used instead of generating
1594 * the default gallery template.
1597 * @since 4.2.0 The `$instance` parameter was added.
1599 * @see gallery_shortcode()
1601 * @param string $output The gallery output. Default empty.
1602 * @param array $attr Attributes of the gallery shortcode.
1603 * @param int $instance Unique numeric ID of this gallery shortcode instance.
1605 $output = apply_filters( 'post_gallery', '', $attr, $instance );
1606 if ( $output != '' ) {
1610 $html5 = current_theme_supports( 'html5', 'gallery' );
1611 $atts = shortcode_atts( array(
1613 'orderby' => 'menu_order ID',
1614 'id' => $post ? $post->ID : 0,
1615 'itemtag' => $html5 ? 'figure' : 'dl',
1616 'icontag' => $html5 ? 'div' : 'dt',
1617 'captiontag' => $html5 ? 'figcaption' : 'dd',
1619 'size' => 'thumbnail',
1623 ), $attr, 'gallery' );
1625 $id = intval( $atts['id'] );
1627 if ( ! empty( $atts['include'] ) ) {
1628 $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1630 $attachments = array();
1631 foreach ( $_attachments as $key => $val ) {
1632 $attachments[$val->ID] = $_attachments[$key];
1634 } elseif ( ! empty( $atts['exclude'] ) ) {
1635 $attachments = get_children( array( 'post_parent' => $id, 'exclude' => $atts['exclude'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1637 $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1640 if ( empty( $attachments ) ) {
1646 foreach ( $attachments as $att_id => $attachment ) {
1647 $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
1652 $itemtag = tag_escape( $atts['itemtag'] );
1653 $captiontag = tag_escape( $atts['captiontag'] );
1654 $icontag = tag_escape( $atts['icontag'] );
1655 $valid_tags = wp_kses_allowed_html( 'post' );
1656 if ( ! isset( $valid_tags[ $itemtag ] ) ) {
1659 if ( ! isset( $valid_tags[ $captiontag ] ) ) {
1662 if ( ! isset( $valid_tags[ $icontag ] ) ) {
1666 $columns = intval( $atts['columns'] );
1667 $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
1668 $float = is_rtl() ? 'right' : 'left';
1670 $selector = "gallery-{$instance}";
1672 $gallery_style = '';
1675 * Filter whether to print default gallery styles.
1679 * @param bool $print Whether to print default gallery styles.
1680 * Defaults to false if the theme supports HTML5 galleries.
1681 * Otherwise, defaults to true.
1683 if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1685 <style type='text/css'>
1689 #{$selector} .gallery-item {
1693 width: {$itemwidth}%;
1696 border: 2px solid #cfcfcf;
1698 #{$selector} .gallery-caption {
1701 /* see gallery_shortcode() in wp-includes/media.php */
1705 $size_class = sanitize_html_class( $atts['size'] );
1706 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1709 * Filter the default gallery shortcode CSS styles.
1713 * @param string $gallery_style Default CSS styles and opening HTML div container
1714 * for the gallery shortcode output.
1716 $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1719 foreach ( $attachments as $id => $attachment ) {
1721 $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
1722 if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
1723 $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
1724 } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
1725 $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
1727 $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
1729 $image_meta = wp_get_attachment_metadata( $id );
1732 if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
1733 $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1735 $output .= "<{$itemtag} class='gallery-item'>";
1737 <{$icontag} class='gallery-icon {$orientation}'>
1740 if ( $captiontag && trim($attachment->post_excerpt) ) {
1742 <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
1743 " . wptexturize($attachment->post_excerpt) . "
1746 $output .= "</{$itemtag}>";
1747 if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1748 $output .= '<br style="clear: both" />';
1752 if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1754 <br style='clear: both' />";
1764 * Outputs the templates used by playlists.
1768 function wp_underscore_playlist_templates() {
1770 <script type="text/html" id="tmpl-wp-playlist-current-item">
1771 <# if ( data.image ) { #>
1772 <img src="{{ data.thumb.src }}" alt="" />
1774 <div class="wp-playlist-caption">
1775 <span class="wp-playlist-item-meta wp-playlist-item-title"><?php
1776 /* translators: playlist item title */
1777 printf( _x( '“%s”', 'playlist item title' ), '{{ data.title }}' );
1779 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1780 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1783 <script type="text/html" id="tmpl-wp-playlist-item">
1784 <div class="wp-playlist-item">
1785 <a class="wp-playlist-caption" href="{{ data.src }}">
1786 {{ data.index ? ( data.index + '. ' ) : '' }}
1787 <# if ( data.caption ) { #>
1790 <span class="wp-playlist-item-title"><?php
1791 /* translators: playlist item title */
1792 printf( _x( '“%s”', 'playlist item title' ), '{{{ data.title }}}' );
1794 <# if ( data.artists && data.meta.artist ) { #>
1795 <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span>
1799 <# if ( data.meta.length_formatted ) { #>
1800 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1808 * Outputs and enqueue default scripts and styles for playlists.
1812 * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1814 function wp_playlist_scripts( $type ) {
1815 wp_enqueue_style( 'wp-mediaelement' );
1816 wp_enqueue_script( 'wp-playlist' );
1818 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1820 add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1821 add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1825 * Builds the Playlist shortcode output.
1827 * This implements the functionality of the playlist shortcode for displaying
1828 * a collection of WordPress audio or video files in a post.
1832 * @global int $content_width
1833 * @staticvar int $instance
1835 * @param array $attr {
1836 * Array of default playlist attributes.
1838 * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
1839 * @type string $order Designates ascending or descending order of items in the playlist.
1840 * Accepts 'ASC', 'DESC'. Default 'ASC'.
1841 * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
1842 * passed, this defaults to the order of the $ids array ('post__in').
1843 * Otherwise default is 'menu_order ID'.
1844 * @type int $id If an explicit $ids array is not present, this parameter
1845 * will determine which attachments are used for the playlist.
1846 * Default is the current post ID.
1847 * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
1848 * a playlist will be created from all $type attachments of $id.
1850 * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
1851 * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
1852 * @type bool $tracklist Whether to show or hide the playlist. Default true.
1853 * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
1854 * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
1855 * thumbnail). Default true.
1856 * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
1859 * @return string Playlist output. Empty string if the passed type is unsupported.
1861 function wp_playlist_shortcode( $attr ) {
1862 global $content_width;
1865 static $instance = 0;
1868 if ( ! empty( $attr['ids'] ) ) {
1869 // 'ids' is explicitly ordered, unless you specify otherwise.
1870 if ( empty( $attr['orderby'] ) ) {
1871 $attr['orderby'] = 'post__in';
1873 $attr['include'] = $attr['ids'];
1877 * Filter the playlist output.
1879 * Passing a non-empty value to the filter will short-circuit generation
1880 * of the default playlist output, returning the passed value instead.
1883 * @since 4.2.0 The `$instance` parameter was added.
1885 * @param string $output Playlist output. Default empty.
1886 * @param array $attr An array of shortcode attributes.
1887 * @param int $instance Unique numeric ID of this playlist shortcode instance.
1889 $output = apply_filters( 'post_playlist', '', $attr, $instance );
1890 if ( $output != '' ) {
1894 $atts = shortcode_atts( array(
1897 'orderby' => 'menu_order ID',
1898 'id' => $post ? $post->ID : 0,
1902 'tracklist' => true,
1903 'tracknumbers' => true,
1906 ), $attr, 'playlist' );
1908 $id = intval( $atts['id'] );
1910 if ( $atts['type'] !== 'audio' ) {
1911 $atts['type'] = 'video';
1915 'post_status' => 'inherit',
1916 'post_type' => 'attachment',
1917 'post_mime_type' => $atts['type'],
1918 'order' => $atts['order'],
1919 'orderby' => $atts['orderby']
1922 if ( ! empty( $atts['include'] ) ) {
1923 $args['include'] = $atts['include'];
1924 $_attachments = get_posts( $args );
1926 $attachments = array();
1927 foreach ( $_attachments as $key => $val ) {
1928 $attachments[$val->ID] = $_attachments[$key];
1930 } elseif ( ! empty( $atts['exclude'] ) ) {
1931 $args['post_parent'] = $id;
1932 $args['exclude'] = $atts['exclude'];
1933 $attachments = get_children( $args );
1935 $args['post_parent'] = $id;
1936 $attachments = get_children( $args );
1939 if ( empty( $attachments ) ) {
1945 foreach ( $attachments as $att_id => $attachment ) {
1946 $output .= wp_get_attachment_link( $att_id ) . "\n";
1951 $outer = 22; // default padding and border of wrapper
1953 $default_width = 640;
1954 $default_height = 360;
1956 $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
1957 $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
1960 'type' => $atts['type'],
1961 // don't pass strings to JSON, will be truthy in JS
1962 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
1963 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
1964 'images' => wp_validate_boolean( $atts['images'] ),
1965 'artists' => wp_validate_boolean( $atts['artists'] ),
1969 foreach ( $attachments as $attachment ) {
1970 $url = wp_get_attachment_url( $attachment->ID );
1971 $ftype = wp_check_filetype( $url, wp_get_mime_types() );
1974 'type' => $ftype['type'],
1975 'title' => $attachment->post_title,
1976 'caption' => $attachment->post_excerpt,
1977 'description' => $attachment->post_content
1980 $track['meta'] = array();
1981 $meta = wp_get_attachment_metadata( $attachment->ID );
1982 if ( ! empty( $meta ) ) {
1984 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
1985 if ( ! empty( $meta[ $key ] ) ) {
1986 $track['meta'][ $key ] = $meta[ $key ];
1990 if ( 'video' === $atts['type'] ) {
1991 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1992 $width = $meta['width'];
1993 $height = $meta['height'];
1994 $theme_height = round( ( $height * $theme_width ) / $width );
1996 $width = $default_width;
1997 $height = $default_height;
2000 $track['dimensions'] = array(
2001 'original' => compact( 'width', 'height' ),
2003 'width' => $theme_width,
2004 'height' => $theme_height
2010 if ( $atts['images'] ) {
2011 $thumb_id = get_post_thumbnail_id( $attachment->ID );
2012 if ( ! empty( $thumb_id ) ) {
2013 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
2014 $track['image'] = compact( 'src', 'width', 'height' );
2015 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
2016 $track['thumb'] = compact( 'src', 'width', 'height' );
2018 $src = wp_mime_type_icon( $attachment->ID );
2021 $track['image'] = compact( 'src', 'width', 'height' );
2022 $track['thumb'] = compact( 'src', 'width', 'height' );
2028 $data['tracks'] = $tracks;
2030 $safe_type = esc_attr( $atts['type'] );
2031 $safe_style = esc_attr( $atts['style'] );
2035 if ( 1 === $instance ) {
2037 * Print and enqueue playlist scripts, styles, and JavaScript templates.
2041 * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
2042 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
2044 do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
2046 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
2047 <?php if ( 'audio' === $atts['type'] ): ?>
2048 <div class="wp-playlist-current-item"></div>
2050 <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
2051 echo (int) $theme_width;
2052 ?>"<?php if ( 'video' === $safe_type ):
2053 echo ' height="', (int) $theme_height, '"';
2055 echo ' style="visibility: hidden"';
2056 endif; ?>></<?php echo $safe_type ?>>
2057 <div class="wp-playlist-next"></div>
2058 <div class="wp-playlist-prev"></div>
2061 foreach ( $attachments as $att_id => $attachment ) {
2062 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
2066 <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
2069 return ob_get_clean();
2071 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
2074 * Provides a No-JS Flash fallback as a last resort for audio / video.
2078 * @param string $url The media element URL.
2079 * @return string Fallback HTML.
2081 function wp_mediaelement_fallback( $url ) {
2083 * Filter the Mediaelement fallback output for no-JS.
2087 * @param string $output Fallback output for no-JS.
2088 * @param string $url Media file URL.
2090 return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
2094 * Returns a filtered list of WP-supported audio formats.
2098 * @return array Supported audio formats.
2100 function wp_get_audio_extensions() {
2102 * Filter the list of supported audio formats.
2106 * @param array $extensions An array of support audio formats. Defaults are
2107 * 'mp3', 'ogg', 'wma', 'm4a', 'wav'.
2109 return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
2113 * Returns useful keys to use to lookup data from an attachment's stored metadata.
2117 * @param WP_Post $attachment The current attachment, provided for context.
2118 * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'.
2119 * @return array Key/value pairs of field keys to labels.
2121 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
2123 'artist' => __( 'Artist' ),
2124 'album' => __( 'Album' ),
2127 if ( 'display' === $context ) {
2128 $fields['genre'] = __( 'Genre' );
2129 $fields['year'] = __( 'Year' );
2130 $fields['length_formatted'] = _x( 'Length', 'video or audio' );
2131 } elseif ( 'js' === $context ) {
2132 $fields['bitrate'] = __( 'Bitrate' );
2133 $fields['bitrate_mode'] = __( 'Bitrate Mode' );
2137 * Filter the editable list of keys to look up data from an attachment's metadata.
2141 * @param array $fields Key/value pairs of field keys to labels.
2142 * @param WP_Post $attachment Attachment object.
2143 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
2145 return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
2148 * Builds the Audio shortcode output.
2150 * This implements the functionality of the Audio Shortcode for displaying
2151 * WordPress mp3s in a post.
2155 * @staticvar int $instance
2157 * @param array $attr {
2158 * Attributes of the audio shortcode.
2160 * @type string $src URL to the source of the audio file. Default empty.
2161 * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
2162 * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
2163 * @type string $preload The 'preload' attribute for the `<audio>` element. Default empty.
2164 * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
2165 * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
2167 * @param string $content Shortcode content.
2168 * @return string|void HTML content to display audio.
2170 function wp_audio_shortcode( $attr, $content = '' ) {
2171 $post_id = get_post() ? get_the_ID() : 0;
2173 static $instance = 0;
2177 * Filter the default audio shortcode output.
2179 * If the filtered output isn't empty, it will be used instead of generating the default audio template.
2183 * @param string $html Empty variable to be replaced with shortcode markup.
2184 * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
2185 * @param string $content Shortcode content.
2186 * @param int $instance Unique numeric ID of this audio shortcode instance.
2188 $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
2189 if ( '' !== $override ) {
2195 $default_types = wp_get_audio_extensions();
2196 $defaults_atts = array(
2202 foreach ( $default_types as $type ) {
2203 $defaults_atts[$type] = '';
2206 $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
2209 if ( ! empty( $atts['src'] ) ) {
2210 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2211 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
2212 return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2215 array_unshift( $default_types, 'src' );
2217 foreach ( $default_types as $ext ) {
2218 if ( ! empty( $atts[ $ext ] ) ) {
2219 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2220 if ( strtolower( $type['ext'] ) === $ext ) {
2228 $audios = get_attached_media( 'audio', $post_id );
2229 if ( empty( $audios ) ) {
2233 $audio = reset( $audios );
2234 $atts['src'] = wp_get_attachment_url( $audio->ID );
2235 if ( empty( $atts['src'] ) ) {
2239 array_unshift( $default_types, 'src' );
2243 * Filter the media library used for the audio shortcode.
2247 * @param string $library Media library used for the audio shortcode.
2249 $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
2250 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
2251 wp_enqueue_style( 'wp-mediaelement' );
2252 wp_enqueue_script( 'wp-mediaelement' );
2256 * Filter the class attribute for the audio shortcode output container.
2260 * @param string $class CSS class or list of space-separated classes.
2263 'class' => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
2264 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
2265 'loop' => wp_validate_boolean( $atts['loop'] ),
2266 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
2267 'preload' => $atts['preload'],
2268 'style' => 'width: 100%; visibility: hidden;',
2271 // These ones should just be omitted altogether if they are blank
2272 foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
2273 if ( empty( $html_atts[$a] ) ) {
2274 unset( $html_atts[$a] );
2278 $attr_strings = array();
2279 foreach ( $html_atts as $k => $v ) {
2280 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
2284 if ( 'mediaelement' === $library && 1 === $instance ) {
2285 $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
2287 $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
2290 $source = '<source type="%s" src="%s" />';
2291 foreach ( $default_types as $fallback ) {
2292 if ( ! empty( $atts[ $fallback ] ) ) {
2293 if ( empty( $fileurl ) ) {
2294 $fileurl = $atts[ $fallback ];
2296 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
2297 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
2298 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
2302 if ( 'mediaelement' === $library ) {
2303 $html .= wp_mediaelement_fallback( $fileurl );
2305 $html .= '</audio>';
2308 * Filter the audio shortcode output.
2312 * @param string $html Audio shortcode HTML output.
2313 * @param array $atts Array of audio shortcode attributes.
2314 * @param string $audio Audio file.
2315 * @param int $post_id Post ID.
2316 * @param string $library Media library used for the audio shortcode.
2318 return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
2320 add_shortcode( 'audio', 'wp_audio_shortcode' );
2323 * Returns a filtered list of WP-supported video formats.
2327 * @return array List of supported video formats.
2329 function wp_get_video_extensions() {
2331 * Filter the list of supported video formats.
2335 * @param array $extensions An array of support video formats. Defaults are
2336 * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
2338 return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
2342 * Builds the Video shortcode output.
2344 * This implements the functionality of the Video Shortcode for displaying
2345 * WordPress mp4s in a post.
2349 * @global int $content_width
2350 * @staticvar int $instance
2352 * @param array $attr {
2353 * Attributes of the shortcode.
2355 * @type string $src URL to the source of the video file. Default empty.
2356 * @type int $height Height of the video embed in pixels. Default 360.
2357 * @type int $width Width of the video embed in pixels. Default $content_width or 640.
2358 * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
2359 * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
2360 * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
2361 * @type string $preload The 'preload' attribute for the `<video>` element.
2362 * Default 'metadata'.
2363 * @type string $class The 'class' attribute for the `<video>` element.
2364 * Default 'wp-video-shortcode'.
2366 * @param string $content Shortcode content.
2367 * @return string|void HTML content to display video.
2369 function wp_video_shortcode( $attr, $content = '' ) {
2370 global $content_width;
2371 $post_id = get_post() ? get_the_ID() : 0;
2373 static $instance = 0;
2377 * Filter the default video shortcode output.
2379 * If the filtered output isn't empty, it will be used instead of generating
2380 * the default video template.
2384 * @see wp_video_shortcode()
2386 * @param string $html Empty variable to be replaced with shortcode markup.
2387 * @param array $attr Attributes of the video shortcode.
2388 * @param string $content Video shortcode content.
2389 * @param int $instance Unique numeric ID of this video shortcode instance.
2391 $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
2392 if ( '' !== $override ) {
2398 $default_types = wp_get_video_extensions();
2399 $defaults_atts = array(
2404 'preload' => 'metadata',
2409 foreach ( $default_types as $type ) {
2410 $defaults_atts[$type] = '';
2413 $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
2416 // shrink the video so it isn't huge in the admin
2417 if ( $atts['width'] > $defaults_atts['width'] ) {
2418 $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
2419 $atts['width'] = $defaults_atts['width'];
2422 // if the video is bigger than the theme
2423 if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
2424 $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
2425 $atts['width'] = $content_width;
2429 $is_vimeo = $is_youtube = false;
2430 $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
2431 $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
2434 if ( ! empty( $atts['src'] ) ) {
2435 $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
2436 $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
2437 if ( ! $is_youtube && ! $is_vimeo ) {
2438 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2439 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
2440 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2445 wp_enqueue_script( 'froogaloop' );
2449 array_unshift( $default_types, 'src' );
2451 foreach ( $default_types as $ext ) {
2452 if ( ! empty( $atts[ $ext ] ) ) {
2453 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2454 if ( strtolower( $type['ext'] ) === $ext ) {
2462 $videos = get_attached_media( 'video', $post_id );
2463 if ( empty( $videos ) ) {
2467 $video = reset( $videos );
2468 $atts['src'] = wp_get_attachment_url( $video->ID );
2469 if ( empty( $atts['src'] ) ) {
2473 array_unshift( $default_types, 'src' );
2477 * Filter the media library used for the video shortcode.
2481 * @param string $library Media library used for the video shortcode.
2483 $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
2484 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
2485 wp_enqueue_style( 'wp-mediaelement' );
2486 wp_enqueue_script( 'wp-mediaelement' );
2490 * Filter the class attribute for the video shortcode output container.
2494 * @param string $class CSS class or list of space-separated classes.
2497 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
2498 'id' => sprintf( 'video-%d-%d', $post_id, $instance ),
2499 'width' => absint( $atts['width'] ),
2500 'height' => absint( $atts['height'] ),
2501 'poster' => esc_url( $atts['poster'] ),
2502 'loop' => wp_validate_boolean( $atts['loop'] ),
2503 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
2504 'preload' => $atts['preload'],
2507 // These ones should just be omitted altogether if they are blank
2508 foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
2509 if ( empty( $html_atts[$a] ) ) {
2510 unset( $html_atts[$a] );
2514 $attr_strings = array();
2515 foreach ( $html_atts as $k => $v ) {
2516 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
2520 if ( 'mediaelement' === $library && 1 === $instance ) {
2521 $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
2523 $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
2526 $source = '<source type="%s" src="%s" />';
2527 foreach ( $default_types as $fallback ) {
2528 if ( ! empty( $atts[ $fallback ] ) ) {
2529 if ( empty( $fileurl ) ) {
2530 $fileurl = $atts[ $fallback ];
2532 if ( 'src' === $fallback && $is_youtube ) {
2533 $type = array( 'type' => 'video/youtube' );
2534 } elseif ( 'src' === $fallback && $is_vimeo ) {
2535 $type = array( 'type' => 'video/vimeo' );
2537 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
2539 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
2540 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
2544 if ( ! empty( $content ) ) {
2545 if ( false !== strpos( $content, "\n" ) ) {
2546 $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
2548 $html .= trim( $content );
2551 if ( 'mediaelement' === $library ) {
2552 $html .= wp_mediaelement_fallback( $fileurl );
2554 $html .= '</video>';
2557 if ( ! empty( $atts['width'] ) ) {
2558 $width_rule = sprintf( 'width: %dpx; ', $atts['width'] );
2560 $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
2563 * Filter the output of the video shortcode.
2567 * @param string $output Video shortcode HTML output.
2568 * @param array $atts Array of video shortcode attributes.
2569 * @param string $video Video file.
2570 * @param int $post_id Post ID.
2571 * @param string $library Media library used for the video shortcode.
2573 return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
2575 add_shortcode( 'video', 'wp_video_shortcode' );
2578 * Displays previous image link that has the same post parent.
2582 * @see adjacent_image_link()
2584 * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
2585 * height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
2586 * default to 'post_title' or `$text`. Default 'thumbnail'.
2587 * @param string $text Optional. Link text. Default false.
2589 function previous_image_link( $size = 'thumbnail', $text = false ) {
2590 adjacent_image_link(true, $size, $text);
2594 * Displays next image link that has the same post parent.
2598 * @see adjacent_image_link()
2600 * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
2601 * height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
2602 * default to 'post_title' or `$text`. Default 'thumbnail'.
2603 * @param string $text Optional. Link text. Default false.
2605 function next_image_link( $size = 'thumbnail', $text = false ) {
2606 adjacent_image_link(false, $size, $text);
2610 * Displays next or previous image link that has the same post parent.
2612 * Retrieves the current attachment object from the $post global.
2616 * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
2617 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width and height
2618 * values in pixels (in that order). Default 'thumbnail'.
2619 * @param bool $text Optional. Link text. Default false.
2621 function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
2623 $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) );
2625 foreach ( $attachments as $k => $attachment ) {
2626 if ( $attachment->ID == $post->ID ) {
2634 if ( $attachments ) {
2635 $k = $prev ? $k - 1 : $k + 1;
2637 if ( isset( $attachments[ $k ] ) ) {
2638 $attachment_id = $attachments[ $k ]->ID;
2639 $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
2643 $adjacent = $prev ? 'previous' : 'next';
2646 * Filter the adjacent image link.
2648 * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
2649 * either 'next', or 'previous'.
2653 * @param string $output Adjacent image HTML markup.
2654 * @param int $attachment_id Attachment ID
2655 * @param string $size Image size.
2656 * @param string $text Link text.
2658 echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
2662 * Retrieves taxonomies attached to given the attachment.
2666 * @param int|array|object $attachment Attachment ID, data array, or data object.
2667 * @return array Empty array on failure. List of taxonomies on success.
2669 function get_attachment_taxonomies( $attachment ) {
2670 if ( is_int( $attachment ) ) {
2671 $attachment = get_post( $attachment );
2672 } elseif ( is_array( $attachment ) ) {
2673 $attachment = (object) $attachment;
2675 if ( ! is_object($attachment) )
2678 $file = get_attached_file( $attachment->ID );
2679 $filename = basename( $file );
2681 $objects = array('attachment');
2683 if ( false !== strpos($filename, '.') )
2684 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
2685 if ( !empty($attachment->post_mime_type) ) {
2686 $objects[] = 'attachment:' . $attachment->post_mime_type;
2687 if ( false !== strpos($attachment->post_mime_type, '/') )
2688 foreach ( explode('/', $attachment->post_mime_type) as $token )
2689 if ( !empty($token) )
2690 $objects[] = "attachment:$token";
2693 $taxonomies = array();
2694 foreach ( $objects as $object )
2695 if ( $taxes = get_object_taxonomies($object) )
2696 $taxonomies = array_merge($taxonomies, $taxes);
2698 return array_unique($taxonomies);
2702 * Retrieves all of the taxonomy names that are registered for attachments.
2704 * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
2708 * @see get_taxonomies()
2710 * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
2712 * @return array The names of all taxonomy of $object_type.
2714 function get_taxonomies_for_attachments( $output = 'names' ) {
2715 $taxonomies = array();
2716 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
2717 foreach ( $taxonomy->object_type as $object_type ) {
2718 if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
2719 if ( 'names' == $output )
2720 $taxonomies[] = $taxonomy->name;
2722 $taxonomies[ $taxonomy->name ] = $taxonomy;
2732 * Create new GD image resource with transparency support
2734 * @todo: Deprecate if possible.
2738 * @param int $width Image width in pixels.
2739 * @param int $height Image height in pixels..
2740 * @return resource The GD image resource.
2742 function wp_imagecreatetruecolor($width, $height) {
2743 $img = imagecreatetruecolor($width, $height);
2744 if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
2745 imagealphablending($img, false);
2746 imagesavealpha($img, true);
2752 * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
2756 * @see wp_constrain_dimensions()
2758 * @param int $example_width The width of an example embed.
2759 * @param int $example_height The height of an example embed.
2760 * @param int $max_width The maximum allowed width.
2761 * @param int $max_height The maximum allowed height.
2762 * @return array The maximum possible width and height based on the example ratio.
2764 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
2765 $example_width = (int) $example_width;
2766 $example_height = (int) $example_height;
2767 $max_width = (int) $max_width;
2768 $max_height = (int) $max_height;
2770 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
2774 * Converts a shorthand byte value to an integer byte value.
2778 * @param string $size A shorthand byte value.
2779 * @return int An integer byte value.
2781 function wp_convert_hr_to_bytes( $size ) {
2782 $size = strtolower( $size );
2783 $bytes = (int) $size;
2784 if ( strpos( $size, 'k' ) !== false )
2785 $bytes = intval( $size ) * KB_IN_BYTES;
2786 elseif ( strpos( $size, 'm' ) !== false )
2787 $bytes = intval($size) * MB_IN_BYTES;
2788 elseif ( strpos( $size, 'g' ) !== false )
2789 $bytes = intval( $size ) * GB_IN_BYTES;
2794 * Determines the maximum upload size allowed in php.ini.
2798 * @return int Allowed upload size.
2800 function wp_max_upload_size() {
2801 $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2802 $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2805 * Filter the maximum upload size allowed in php.ini.
2809 * @param int $size Max upload size limit in bytes.
2810 * @param int $u_bytes Maximum upload filesize in bytes.
2811 * @param int $p_bytes Maximum size of POST data in bytes.
2813 return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2817 * Returns a WP_Image_Editor instance and loads file into it.
2821 * @param string $path Path to the file to load.
2822 * @param array $args Optional. Additional arguments for retrieving the image editor.
2823 * Default empty array.
2824 * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
2827 function wp_get_image_editor( $path, $args = array() ) {
2828 $args['path'] = $path;
2830 if ( ! isset( $args['mime_type'] ) ) {
2831 $file_info = wp_check_filetype( $args['path'] );
2833 // If $file_info['type'] is false, then we let the editor attempt to
2834 // figure out the file type, rather than forcing a failure based on extension.
2835 if ( isset( $file_info ) && $file_info['type'] )
2836 $args['mime_type'] = $file_info['type'];
2839 $implementation = _wp_image_editor_choose( $args );
2841 if ( $implementation ) {
2842 $editor = new $implementation( $path );
2843 $loaded = $editor->load();
2845 if ( is_wp_error( $loaded ) )
2851 return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
2855 * Tests whether there is an editor that supports a given mime type or methods.
2859 * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
2860 * Default empty array.
2861 * @return bool True if an eligible editor is found; false otherwise.
2863 function wp_image_editor_supports( $args = array() ) {
2864 return (bool) _wp_image_editor_choose( $args );
2868 * Tests which editors are capable of supporting the request.
2873 * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
2874 * @return string|false Class name for the first editor that claims to support the request. False if no
2875 * editor claims to support the request.
2877 function _wp_image_editor_choose( $args = array() ) {
2878 require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
2879 require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
2880 require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
2883 * Filter the list of image editing library classes.
2887 * @param array $image_editors List of available image editors. Defaults are
2888 * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
2890 $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
2892 foreach ( $implementations as $implementation ) {
2893 if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
2896 if ( isset( $args['mime_type'] ) &&
2898 array( $implementation, 'supports_mime_type' ),
2899 $args['mime_type'] ) ) {
2903 if ( isset( $args['methods'] ) &&
2904 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
2908 return $implementation;
2915 * Prints default plupload arguments.
2919 function wp_plupload_default_settings() {
2920 $wp_scripts = wp_scripts();
2922 $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
2923 if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
2926 $max_upload_size = wp_max_upload_size();
2929 'runtimes' => 'html5,flash,silverlight,html4',
2930 'file_data_name' => 'async-upload', // key passed to $_FILE.
2931 'url' => admin_url( 'async-upload.php', 'relative' ),
2932 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
2933 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
2935 'max_file_size' => $max_upload_size . 'b',
2939 // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
2940 // when enabled. See #29602.
2941 if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
2942 strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
2944 $defaults['multi_selection'] = false;
2948 * Filter the Plupload default settings.
2952 * @param array $defaults Default Plupload settings array.
2954 $defaults = apply_filters( 'plupload_default_settings', $defaults );
2957 'action' => 'upload-attachment',
2961 * Filter the Plupload default parameters.
2965 * @param array $params Default Plupload parameters array.
2967 $params = apply_filters( 'plupload_default_params', $params );
2968 $params['_wpnonce'] = wp_create_nonce( 'media-form' );
2969 $defaults['multipart_params'] = $params;
2972 'defaults' => $defaults,
2974 'mobile' => wp_is_mobile(),
2975 'supported' => _device_can_upload(),
2977 'limitExceeded' => is_multisite() && ! is_upload_space_available()
2980 $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
2983 $script = "$data\n$script";
2985 $wp_scripts->add_data( 'wp-plupload', 'data', $script );
2989 * Prepares an attachment post object for JS, where it is expected
2990 * to be JSON-encoded and fit into an Attachment model.
2994 * @param mixed $attachment Attachment ID or object.
2995 * @return array|void Array of attachment details.
2997 function wp_prepare_attachment_for_js( $attachment ) {
2998 if ( ! $attachment = get_post( $attachment ) )
3001 if ( 'attachment' != $attachment->post_type )
3004 $meta = wp_get_attachment_metadata( $attachment->ID );
3005 if ( false !== strpos( $attachment->post_mime_type, '/' ) )
3006 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
3008 list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
3010 $attachment_url = wp_get_attachment_url( $attachment->ID );
3013 'id' => $attachment->ID,
3014 'title' => $attachment->post_title,
3015 'filename' => wp_basename( get_attached_file( $attachment->ID ) ),
3016 'url' => $attachment_url,
3017 'link' => get_attachment_link( $attachment->ID ),
3018 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
3019 'author' => $attachment->post_author,
3020 'description' => $attachment->post_content,
3021 'caption' => $attachment->post_excerpt,
3022 'name' => $attachment->post_name,
3023 'status' => $attachment->post_status,
3024 'uploadedTo' => $attachment->post_parent,
3025 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
3026 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
3027 'menuOrder' => $attachment->menu_order,
3028 'mime' => $attachment->post_mime_type,
3030 'subtype' => $subtype,
3031 'icon' => wp_mime_type_icon( $attachment->ID ),
3032 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
3038 'editLink' => false,
3042 $author = new WP_User( $attachment->post_author );
3043 $response['authorName'] = $author->display_name;
3045 if ( $attachment->post_parent ) {
3046 $post_parent = get_post( $attachment->post_parent );
3048 $post_parent = false;
3051 if ( $post_parent ) {
3052 $parent_type = get_post_type_object( $post_parent->post_type );
3053 if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
3054 $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
3056 $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
3059 $attached_file = get_attached_file( $attachment->ID );
3061 if ( isset( $meta['filesize'] ) ) {
3062 $bytes = $meta['filesize'];
3063 } elseif ( file_exists( $attached_file ) ) {
3064 $bytes = filesize( $attached_file );
3070 $response['filesizeInBytes'] = $bytes;
3071 $response['filesizeHumanReadable'] = size_format( $bytes );
3074 if ( current_user_can( 'edit_post', $attachment->ID ) ) {
3075 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
3076 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
3077 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
3080 if ( current_user_can( 'delete_post', $attachment->ID ) )
3081 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
3083 if ( $meta && 'image' === $type ) {
3086 /** This filter is documented in wp-admin/includes/media.php */
3087 $possible_sizes = apply_filters( 'image_size_names_choose', array(
3088 'thumbnail' => __('Thumbnail'),
3089 'medium' => __('Medium'),
3090 'large' => __('Large'),
3091 'full' => __('Full Size'),
3093 unset( $possible_sizes['full'] );
3095 // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
3096 // First: run the image_downsize filter. If it returns something, we can use its data.
3097 // If the filter does not return something, then image_downsize() is just an expensive
3098 // way to check the image metadata, which we do second.
3099 foreach ( $possible_sizes as $size => $label ) {
3101 /** This filter is documented in wp-includes/media.php */
3102 if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
3103 if ( ! $downsize[3] )
3105 $sizes[ $size ] = array(
3106 'height' => $downsize[2],
3107 'width' => $downsize[1],
3108 'url' => $downsize[0],
3109 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
3111 } elseif ( isset( $meta['sizes'][ $size ] ) ) {
3112 if ( ! isset( $base_url ) )
3113 $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
3115 // Nothing from the filter, so consult image metadata if we have it.
3116 $size_meta = $meta['sizes'][ $size ];
3118 // We have the actual image size, but might need to further constrain it if content_width is narrower.
3119 // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
3120 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
3122 $sizes[ $size ] = array(
3123 'height' => $height,
3125 'url' => $base_url . $size_meta['file'],
3126 'orientation' => $height > $width ? 'portrait' : 'landscape',
3131 $sizes['full'] = array( 'url' => $attachment_url );
3133 if ( isset( $meta['height'], $meta['width'] ) ) {
3134 $sizes['full']['height'] = $meta['height'];
3135 $sizes['full']['width'] = $meta['width'];
3136 $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
3139 $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
3140 } elseif ( $meta && 'video' === $type ) {
3141 if ( isset( $meta['width'] ) )
3142 $response['width'] = (int) $meta['width'];
3143 if ( isset( $meta['height'] ) )
3144 $response['height'] = (int) $meta['height'];
3147 if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
3148 if ( isset( $meta['length_formatted'] ) )
3149 $response['fileLength'] = $meta['length_formatted'];
3151 $response['meta'] = array();
3152 foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
3153 $response['meta'][ $key ] = false;
3155 if ( ! empty( $meta[ $key ] ) ) {
3156 $response['meta'][ $key ] = $meta[ $key ];
3160 $id = get_post_thumbnail_id( $attachment->ID );
3161 if ( ! empty( $id ) ) {
3162 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
3163 $response['image'] = compact( 'src', 'width', 'height' );
3164 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
3165 $response['thumb'] = compact( 'src', 'width', 'height' );
3167 $src = wp_mime_type_icon( $attachment->ID );
3170 $response['image'] = compact( 'src', 'width', 'height' );
3171 $response['thumb'] = compact( 'src', 'width', 'height' );
3175 if ( function_exists('get_compat_media_markup') )
3176 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
3179 * Filter the attachment data prepared for JavaScript.
3183 * @param array $response Array of prepared attachment data.
3184 * @param int|object $attachment Attachment ID or object.
3185 * @param array $meta Array of attachment meta data.
3187 return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
3191 * Enqueues all scripts, styles, settings, and templates necessary to use
3192 * all media JS APIs.
3196 * @global int $content_width
3197 * @global wpdb $wpdb
3198 * @global WP_Locale $wp_locale
3200 * @param array $args {
3201 * Arguments for enqueuing media scripts.
3203 * @type int|WP_Post A post object or ID.
3206 function wp_enqueue_media( $args = array() ) {
3207 // Enqueue me just once per page, please.
3208 if ( did_action( 'wp_enqueue_media' ) )
3211 global $content_width, $wpdb, $wp_locale;
3216 $args = wp_parse_args( $args, $defaults );
3218 // We're going to pass the old thickbox media tabs to `media_upload_tabs`
3219 // to ensure plugins will work. We will then unset those tabs.
3221 // handler action suffix => tab label
3228 /** This filter is documented in wp-admin/includes/media.php */
3229 $tabs = apply_filters( 'media_upload_tabs', $tabs );
3230 unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
3233 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
3234 'align' => get_option( 'image_default_align' ), // empty default
3235 'size' => get_option( 'image_default_size' ), // empty default
3238 $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
3239 $mimes = get_allowed_mime_types();
3240 $ext_mimes = array();
3241 foreach ( $exts as $ext ) {
3242 foreach ( $mimes as $ext_preg => $mime_match ) {
3243 if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
3244 $ext_mimes[ $ext ] = $mime_match;
3250 $has_audio = $wpdb->get_var( "
3253 WHERE post_type = 'attachment'
3254 AND post_mime_type LIKE 'audio%'
3257 $has_video = $wpdb->get_var( "
3260 WHERE post_type = 'attachment'
3261 AND post_mime_type LIKE 'video%'
3264 $months = $wpdb->get_results( $wpdb->prepare( "
3265 SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
3267 WHERE post_type = %s
3268 ORDER BY post_date DESC
3269 ", 'attachment' ) );
3270 foreach ( $months as $month_year ) {
3271 $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
3276 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
3277 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
3278 /** This filter is documented in wp-admin/includes/media.php */
3279 'captions' => ! apply_filters( 'disable_captions', '' ),
3281 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
3286 'defaultProps' => $props,
3287 'attachmentCounts' => array(
3288 'audio' => ( $has_audio ) ? 1 : 0,
3289 'video' => ( $has_video ) ? 1 : 0
3291 'embedExts' => $exts,
3292 'embedMimes' => $ext_mimes,
3293 'contentWidth' => $content_width,
3294 'months' => $months,
3295 'mediaTrash' => MEDIA_TRASH ? 1 : 0
3299 if ( isset( $args['post'] ) ) {
3300 $post = get_post( $args['post'] );
3301 $settings['post'] = array(
3303 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
3306 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
3307 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
3308 if ( wp_attachment_is( 'audio', $post ) ) {
3309 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
3310 } elseif ( wp_attachment_is( 'video', $post ) ) {
3311 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
3315 if ( $thumbnail_support ) {
3316 $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
3317 $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
3322 $post_type_object = get_post_type_object( $post->post_type );
3324 $post_type_object = get_post_type_object( 'post' );
3329 'url' => __( 'URL' ),
3330 'addMedia' => __( 'Add Media' ),
3331 'search' => __( 'Search' ),
3332 'select' => __( 'Select' ),
3333 'cancel' => __( 'Cancel' ),
3334 'update' => __( 'Update' ),
3335 'replace' => __( 'Replace' ),
3336 'remove' => __( 'Remove' ),
3337 'back' => __( 'Back' ),
3338 /* translators: This is a would-be plural string used in the media manager.
3339 If there is not a word you can use in your language to avoid issues with the
3340 lack of plural support here, turn it into "selected: %d" then translate it.
3342 'selected' => __( '%d selected' ),
3343 'dragInfo' => __( 'Drag and drop to reorder media files.' ),
3346 'uploadFilesTitle' => __( 'Upload Files' ),
3347 'uploadImagesTitle' => __( 'Upload Images' ),
3350 'mediaLibraryTitle' => __( 'Media Library' ),
3351 'insertMediaTitle' => __( 'Insert Media' ),
3352 'createNewGallery' => __( 'Create a new gallery' ),
3353 'createNewPlaylist' => __( 'Create a new playlist' ),
3354 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
3355 'returnToLibrary' => __( '← Return to library' ),
3356 'allMediaItems' => __( 'All media items' ),
3357 'allDates' => __( 'All dates' ),
3358 'noItemsFound' => __( 'No items found.' ),
3359 'insertIntoPost' => $post_type_object->labels->insert_into_item,
3360 'unattached' => __( 'Unattached' ),
3361 'trash' => _x( 'Trash', 'noun' ),
3362 'uploadedToThisPost' => $post_type_object->labels->uploaded_to_this_item,
3363 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
3364 'warnBulkDelete' => __( "You are about to permanently delete these items.\n 'Cancel' to stop, 'OK' to delete." ),
3365 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
3366 'bulkSelect' => __( 'Bulk Select' ),
3367 'cancelSelection' => __( 'Cancel Selection' ),
3368 'trashSelected' => __( 'Trash Selected' ),
3369 'untrashSelected' => __( 'Untrash Selected' ),
3370 'deleteSelected' => __( 'Delete Selected' ),
3371 'deletePermanently' => __( 'Delete Permanently' ),
3372 'apply' => __( 'Apply' ),
3373 'filterByDate' => __( 'Filter by date' ),
3374 'filterByType' => __( 'Filter by type' ),
3375 'searchMediaLabel' => __( 'Search Media' ),
3376 'noMedia' => __( 'No media attachments found.' ),
3379 'attachmentDetails' => __( 'Attachment Details' ),
3382 'insertFromUrlTitle' => __( 'Insert from URL' ),
3385 'setFeaturedImageTitle' => $post_type_object->labels->featured_image,
3386 'setFeaturedImage' => $post_type_object->labels->set_featured_image,
3389 'createGalleryTitle' => __( 'Create Gallery' ),
3390 'editGalleryTitle' => __( 'Edit Gallery' ),
3391 'cancelGalleryTitle' => __( '← Cancel Gallery' ),
3392 'insertGallery' => __( 'Insert gallery' ),
3393 'updateGallery' => __( 'Update gallery' ),
3394 'addToGallery' => __( 'Add to gallery' ),
3395 'addToGalleryTitle' => __( 'Add to Gallery' ),
3396 'reverseOrder' => __( 'Reverse order' ),
3399 'imageDetailsTitle' => __( 'Image Details' ),
3400 'imageReplaceTitle' => __( 'Replace Image' ),
3401 'imageDetailsCancel' => __( 'Cancel Edit' ),
3402 'editImage' => __( 'Edit Image' ),
3405 'chooseImage' => __( 'Choose Image' ),
3406 'selectAndCrop' => __( 'Select and Crop' ),
3407 'skipCropping' => __( 'Skip Cropping' ),
3408 'cropImage' => __( 'Crop Image' ),
3409 'cropYourImage' => __( 'Crop your image' ),
3410 'cropping' => __( 'Cropping…' ),
3411 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
3412 'cropError' => __( 'There has been an error cropping your image.' ),
3415 'audioDetailsTitle' => __( 'Audio Details' ),
3416 'audioReplaceTitle' => __( 'Replace Audio' ),
3417 'audioAddSourceTitle' => __( 'Add Audio Source' ),
3418 'audioDetailsCancel' => __( 'Cancel Edit' ),
3421 'videoDetailsTitle' => __( 'Video Details' ),
3422 'videoReplaceTitle' => __( 'Replace Video' ),
3423 'videoAddSourceTitle' => __( 'Add Video Source' ),
3424 'videoDetailsCancel' => __( 'Cancel Edit' ),
3425 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
3426 'videoAddTrackTitle' => __( 'Add Subtitles' ),
3429 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
3430 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
3431 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
3432 'cancelPlaylistTitle' => __( '← Cancel Audio Playlist' ),
3433 'insertPlaylist' => __( 'Insert audio playlist' ),
3434 'updatePlaylist' => __( 'Update audio playlist' ),
3435 'addToPlaylist' => __( 'Add to audio playlist' ),
3436 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
3439 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
3440 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
3441 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
3442 'cancelVideoPlaylistTitle' => __( '← Cancel Video Playlist' ),
3443 'insertVideoPlaylist' => __( 'Insert video playlist' ),
3444 'updateVideoPlaylist' => __( 'Update video playlist' ),
3445 'addToVideoPlaylist' => __( 'Add to video playlist' ),
3446 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
3450 * Filter the media view settings.
3454 * @param array $settings List of media view settings.
3455 * @param WP_Post $post Post object.
3457 $settings = apply_filters( 'media_view_settings', $settings, $post );
3460 * Filter the media view strings.
3464 * @param array $strings List of media view strings.
3465 * @param WP_Post $post Post object.
3467 $strings = apply_filters( 'media_view_strings', $strings, $post );
3469 $strings['settings'] = $settings;
3471 // Ensure we enqueue media-editor first, that way media-views is
3472 // registered internally before we try to localize it. see #24724.
3473 wp_enqueue_script( 'media-editor' );
3474 wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
3476 wp_enqueue_script( 'media-audiovideo' );
3477 wp_enqueue_style( 'media-views' );
3479 wp_enqueue_script( 'mce-view' );
3480 wp_enqueue_script( 'image-edit' );
3482 wp_enqueue_style( 'imgareaselect' );
3483 wp_plupload_default_settings();
3485 require_once ABSPATH . WPINC . '/media-template.php';
3486 add_action( 'admin_footer', 'wp_print_media_templates' );
3487 add_action( 'wp_footer', 'wp_print_media_templates' );
3488 add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
3491 * Fires at the conclusion of wp_enqueue_media().
3495 do_action( 'wp_enqueue_media' );
3499 * Retrieves media attached to the passed post.
3503 * @param string $type Mime type.
3504 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3505 * @return array Found attachments.
3507 function get_attached_media( $type, $post = 0 ) {
3508 if ( ! $post = get_post( $post ) )
3512 'post_parent' => $post->ID,
3513 'post_type' => 'attachment',
3514 'post_mime_type' => $type,
3515 'posts_per_page' => -1,
3516 'orderby' => 'menu_order',
3521 * Filter arguments used to retrieve media attached to the given post.
3525 * @param array $args Post query arguments.
3526 * @param string $type Mime type of the desired media.
3527 * @param mixed $post Post ID or object.
3529 $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
3531 $children = get_children( $args );
3534 * Filter the list of media attached to the given post.
3538 * @param array $children Associative array of media attached to the given post.
3539 * @param string $type Mime type of the media desired.
3540 * @param mixed $post Post ID or object.
3542 return (array) apply_filters( 'get_attached_media', $children, $type, $post );
3546 * Check the content blob for an audio, video, object, embed, or iframe tags.
3550 * @param string $content A string which might contain media data.
3551 * @param array $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
3552 * @return array A list of found HTML media embeds.
3554 function get_media_embedded_in_content( $content, $types = null ) {
3558 * Filter the embedded media types that are allowed to be returned from the content blob.
3562 * @param array $allowed_media_types An array of allowed media types. Default media types are
3563 * 'audio', 'video', 'object', 'embed', and 'iframe'.
3565 $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
3567 if ( ! empty( $types ) ) {
3568 if ( ! is_array( $types ) ) {
3569 $types = array( $types );
3572 $allowed_media_types = array_intersect( $allowed_media_types, $types );
3575 $tags = implode( '|', $allowed_media_types );
3577 if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
3578 foreach ( $matches[0] as $match ) {
3587 * Retrieves galleries from the passed post's content.
3591 * @param int|WP_Post $post Post ID or object.
3592 * @param bool $html Optional. Whether to return HTML or data in the array. Default true.
3593 * @return array A list of arrays, each containing gallery data and srcs parsed
3594 * from the expanded shortcode.
3596 function get_post_galleries( $post, $html = true ) {
3597 if ( ! $post = get_post( $post ) )
3600 if ( ! has_shortcode( $post->post_content, 'gallery' ) )
3603 $galleries = array();
3604 if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
3605 foreach ( $matches as $shortcode ) {
3606 if ( 'gallery' === $shortcode[2] ) {
3609 $gallery = do_shortcode_tag( $shortcode );
3611 $galleries[] = $gallery;
3613 preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
3614 if ( ! empty( $src ) ) {
3615 foreach ( $src as $s )
3619 $data = shortcode_parse_atts( $shortcode[3] );
3620 $data['src'] = array_values( array_unique( $srcs ) );
3621 $galleries[] = $data;
3628 * Filter the list of all found galleries in the given post.
3632 * @param array $galleries Associative array of all found post galleries.
3633 * @param WP_Post $post Post object.
3635 return apply_filters( 'get_post_galleries', $galleries, $post );
3639 * Check a specified post's content for gallery and, if present, return the first
3643 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3644 * @param bool $html Optional. Whether to return HTML or data. Default is true.
3645 * @return string|array Gallery data and srcs parsed from the expanded shortcode.
3647 function get_post_gallery( $post = 0, $html = true ) {
3648 $galleries = get_post_galleries( $post, $html );
3649 $gallery = reset( $galleries );
3652 * Filter the first-found post gallery.
3656 * @param array $gallery The first-found post gallery.
3657 * @param int|WP_Post $post Post ID or object.
3658 * @param array $galleries Associative array of all found post galleries.
3660 return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
3664 * Retrieve the image srcs from galleries from a post's content, if present
3668 * @see get_post_galleries()
3670 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3671 * @return array A list of lists, each containing image srcs parsed.
3672 * from an expanded shortcode
3674 function get_post_galleries_images( $post = 0 ) {
3675 $galleries = get_post_galleries( $post, false );
3676 return wp_list_pluck( $galleries, 'src' );
3680 * Checks a post's content for galleries and return the image srcs for the first found gallery
3684 * @see get_post_gallery()
3686 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3687 * @return array A list of a gallery's image srcs in order.
3689 function get_post_gallery_images( $post = 0 ) {
3690 $gallery = get_post_gallery( $post, false );
3691 return empty( $gallery['src'] ) ? array() : $gallery['src'];
3695 * Maybe attempts to generate attachment metadata, if missing.
3699 * @param WP_Post $attachment Attachment object.
3701 function wp_maybe_generate_attachment_metadata( $attachment ) {
3702 if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
3706 $file = get_attached_file( $attachment_id );
3707 $meta = wp_get_attachment_metadata( $attachment_id );
3708 if ( empty( $meta ) && file_exists( $file ) ) {
3709 $_meta = get_post_meta( $attachment_id );
3710 $regeneration_lock = 'wp_generating_att_' . $attachment_id;
3711 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
3712 set_transient( $regeneration_lock, $file );
3713 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
3714 delete_transient( $regeneration_lock );
3720 * Tries to convert an attachment URL into a post ID.
3724 * @global wpdb $wpdb WordPress database abstraction object.
3726 * @param string $url The URL to resolve.
3727 * @return int The found post ID, or 0 on failure.
3729 function attachment_url_to_postid( $url ) {
3732 $dir = wp_upload_dir();
3735 $site_url = parse_url( $dir['url'] );
3736 $image_path = parse_url( $path );
3738 //force the protocols to match if needed
3739 if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
3740 $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
3743 if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
3744 $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
3747 $sql = $wpdb->prepare(
3748 "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
3751 $post_id = $wpdb->get_var( $sql );
3754 * Filter an attachment id found by URL.
3758 * @param int|null $post_id The post_id (if any) found by the function.
3759 * @param string $url The URL being looked up.
3761 return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
3765 * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
3769 * @global string $wp_version
3771 * @return array The relevant CSS file URLs.
3773 function wpview_media_sandbox_styles() {
3774 $version = 'ver=' . $GLOBALS['wp_version'];
3775 $mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
3776 $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
3778 return array( $mediaelement, $wpmediaelement );