3 * WordPress API for media display.
10 * Retrieve additional image sizes.
14 * @global array $_wp_additional_image_sizes
16 * @return array Additional images size data.
18 function wp_get_additional_image_sizes() {
19 global $_wp_additional_image_sizes;
20 if ( ! $_wp_additional_image_sizes ) {
21 $_wp_additional_image_sizes = array();
23 return $_wp_additional_image_sizes;
27 * Scale down the default size of an image.
29 * This is so that the image is a better fit for the editor and theme.
31 * The `$size` parameter accepts either an array or a string. The supported string
32 * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
33 * 128 width and 96 height in pixels. Also supported for the string value is
34 * 'medium', 'medium_large' and 'full'. The 'full' isn't actually supported, but any value other
35 * than the supported will result in the content_width size or 500 if that is
38 * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
39 * called on the calculated array for width and height, respectively. The second
40 * parameter will be the value that was in the $size parameter. The returned
41 * type for the hook is an array with the width as the first element and the
42 * height as the second element.
46 * @global int $content_width
48 * @param int $width Width of the image in pixels.
49 * @param int $height Height of the image in pixels.
50 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array
51 * of width and height values in pixels (in that order).
53 * @param string $context Optional. Could be 'display' (like in a theme) or 'edit'
54 * (like inserting into an editor). Default null.
55 * @return array Width and height of what the result image should resize to.
57 function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
58 global $content_width;
60 $_wp_additional_image_sizes = wp_get_additional_image_sizes();
63 $context = is_admin() ? 'edit' : 'display';
65 if ( is_array($size) ) {
66 $max_width = $size[0];
67 $max_height = $size[1];
69 elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
70 $max_width = intval(get_option('thumbnail_size_w'));
71 $max_height = intval(get_option('thumbnail_size_h'));
72 // last chance thumbnail size defaults
73 if ( !$max_width && !$max_height ) {
78 elseif ( $size == 'medium' ) {
79 $max_width = intval(get_option('medium_size_w'));
80 $max_height = intval(get_option('medium_size_h'));
83 elseif ( $size == 'medium_large' ) {
84 $max_width = intval( get_option( 'medium_large_size_w' ) );
85 $max_height = intval( get_option( 'medium_large_size_h' ) );
87 if ( intval( $content_width ) > 0 ) {
88 $max_width = min( intval( $content_width ), $max_width );
91 elseif ( $size == 'large' ) {
93 * We're inserting a large size image into the editor. If it's a really
94 * big image we'll scale it down to fit reasonably within the editor
95 * itself, and within the theme's content width if it's known. The user
96 * can resize it in the editor if they wish.
98 $max_width = intval(get_option('large_size_w'));
99 $max_height = intval(get_option('large_size_h'));
100 if ( intval($content_width) > 0 ) {
101 $max_width = min( intval($content_width), $max_width );
103 } elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
104 $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
105 $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
106 // Only in admin. Assume that theme authors know what they're doing.
107 if ( intval( $content_width ) > 0 && 'edit' === $context ) {
108 $max_width = min( intval( $content_width ), $max_width );
111 // $size == 'full' has no constraint
114 $max_height = $height;
118 * Filters the maximum image size dimensions for the editor.
122 * @param array $max_image_size An array with the width as the first element,
123 * and the height as the second element.
124 * @param string|array $size Size of what the result image should be.
125 * @param string $context The context the image is being resized for.
126 * Possible values are 'display' (like in a theme)
127 * or 'edit' (like inserting into an editor).
129 list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
131 return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
135 * Retrieve width and height attributes using given width and height values.
137 * Both attributes are required in the sense that both parameters must have a
138 * value, but are optional in that if you set them to false or null, then they
139 * will not be added to the returned string.
141 * You can set the value using a string, but it will only take numeric values.
142 * If you wish to put 'px' after the numbers, then it will be stripped out of
147 * @param int|string $width Image width in pixels.
148 * @param int|string $height Image height in pixels.
149 * @return string HTML attributes for width and, or height.
151 function image_hwstring( $width, $height ) {
154 $out .= 'width="'.intval($width).'" ';
156 $out .= 'height="'.intval($height).'" ';
161 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
163 * Array with image url, width, height, and whether is intermediate size, in
164 * that order is returned on success is returned. $is_intermediate is true if
165 * $url is a resized image, false if it is the original.
167 * The URL might be the original image, or it might be a resized version. This
168 * function won't create a new resized copy, it will just return an already
169 * resized one if it exists.
171 * A plugin may use the {@see 'image_downsize'} filter to hook into and offer image
172 * resizing services for images. The hook must return an array with the same
173 * elements that are returned in the function. The first element being the URL
174 * to the new image that was resized.
178 * @param int $id Attachment ID for image.
179 * @param array|string $size Optional. Image size to scale to. Accepts any valid image size,
180 * or an array of width and height values in pixels (in that order).
182 * @return false|array Array containing the image URL, width, height, and boolean for whether
183 * the image is an intermediate size. False on failure.
185 function image_downsize( $id, $size = 'medium' ) {
186 $is_image = wp_attachment_is_image( $id );
189 * Filters whether to preempt the output of image_downsize().
191 * Passing a truthy value to the filter will effectively short-circuit
192 * down-sizing the image, returning that value as output instead.
196 * @param bool $downsize Whether to short-circuit the image downsize. Default false.
197 * @param int $id Attachment ID for image.
198 * @param array|string $size Size of image. Image size or array of width and height values (in that order).
201 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
205 $img_url = wp_get_attachment_url($id);
206 $meta = wp_get_attachment_metadata($id);
207 $width = $height = 0;
208 $is_intermediate = false;
209 $img_url_basename = wp_basename($img_url);
211 // If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
212 // Otherwise, a non-image type could be returned.
214 if ( ! empty( $meta['sizes'] ) ) {
215 $img_url = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
216 $img_url_basename = $meta['sizes']['full']['file'];
217 $width = $meta['sizes']['full']['width'];
218 $height = $meta['sizes']['full']['height'];
224 // try for a new style intermediate size
225 if ( $intermediate = image_get_intermediate_size($id, $size) ) {
226 $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
227 $width = $intermediate['width'];
228 $height = $intermediate['height'];
229 $is_intermediate = true;
231 elseif ( $size == 'thumbnail' ) {
232 // fall back to the old thumbnail
233 if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
234 $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
237 $is_intermediate = true;
240 if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
241 // any other type: use the real image
242 $width = $meta['width'];
243 $height = $meta['height'];
247 // we have the actual image size, but might need to further constrain it if content_width is narrower
248 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
250 return array( $img_url, $width, $height, $is_intermediate );
257 * Register a new image size.
259 * Cropping behavior for the image size is dependent on the value of $crop:
260 * 1. If false (default), images will be scaled, not cropped.
261 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
262 * - x_crop_position accepts 'left' 'center', or 'right'.
263 * - y_crop_position accepts 'top', 'center', or 'bottom'.
264 * Images will be cropped to the specified dimensions within the defined crop area.
265 * 3. If true, images will be cropped to the specified dimensions using center positions.
269 * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
271 * @param string $name Image size identifier.
272 * @param int $width Image width in pixels.
273 * @param int $height Image height in pixels.
274 * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
275 * An array can specify positioning of the crop area. Default false.
277 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
278 global $_wp_additional_image_sizes;
280 $_wp_additional_image_sizes[ $name ] = array(
281 'width' => absint( $width ),
282 'height' => absint( $height ),
288 * Check if an image size exists.
292 * @param string $name The image size to check.
293 * @return bool True if the image size exists, false if not.
295 function has_image_size( $name ) {
296 $sizes = wp_get_additional_image_sizes();
297 return isset( $sizes[ $name ] );
301 * Remove a new image size.
305 * @global array $_wp_additional_image_sizes
307 * @param string $name The image size to remove.
308 * @return bool True if the image size was successfully removed, false on failure.
310 function remove_image_size( $name ) {
311 global $_wp_additional_image_sizes;
313 if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
314 unset( $_wp_additional_image_sizes[ $name ] );
322 * Registers an image size for the post thumbnail.
326 * @see add_image_size() for details on cropping behavior.
328 * @param int $width Image width in pixels.
329 * @param int $height Image height in pixels.
330 * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
331 * An array can specify positioning of the crop area. Default false.
333 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
334 add_image_size( 'post-thumbnail', $width, $height, $crop );
338 * Gets an img tag for an image attachment, scaling it down if requested.
340 * The {@see 'get_image_tag_class'} filter allows for changing the class name for the
341 * image without having to use regular expressions on the HTML content. The
342 * parameters are: what WordPress will use for the class, the Attachment ID,
343 * image align value, and the size the image should be.
345 * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be
346 * further manipulated by a plugin to change all attribute values and even HTML
351 * @param int $id Attachment ID.
352 * @param string $alt Image Description for the alt attribute.
353 * @param string $title Image Description for the title attribute.
354 * @param string $align Part of the class name for aligning the image.
355 * @param string|array $size Optional. Registered image size to retrieve a tag for. Accepts any
356 * valid image size, or an array of width and height values in pixels
357 * (in that order). Default 'medium'.
358 * @return string HTML IMG element for given image attachment
360 function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
362 list( $img_src, $width, $height ) = image_downsize($id, $size);
363 $hwstring = image_hwstring($width, $height);
365 $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
367 $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
370 * Filters the value of the attachment's image tag class attribute.
374 * @param string $class CSS class name or space-separated list of classes.
375 * @param int $id Attachment ID.
376 * @param string $align Part of the class name for aligning the image.
377 * @param string|array $size Size of image. Image size or array of width and height values (in that order).
380 $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
382 $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
385 * Filters the HTML content for the image tag.
389 * @param string $html HTML content for the image.
390 * @param int $id Attachment ID.
391 * @param string $alt Alternate text.
392 * @param string $title Attachment title.
393 * @param string $align Part of the class name for aligning the image.
394 * @param string|array $size Size of image. Image size or array of width and height values (in that order).
397 return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
401 * Calculates the new dimensions for a down-sampled image.
403 * If either width or height are empty, no constraint is applied on
408 * @param int $current_width Current width of the image.
409 * @param int $current_height Current height of the image.
410 * @param int $max_width Optional. Max width in pixels to constrain to. Default 0.
411 * @param int $max_height Optional. Max height in pixels to constrain to. Default 0.
412 * @return array First item is the width, the second item is the height.
414 function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
415 if ( !$max_width && !$max_height )
416 return array( $current_width, $current_height );
418 $width_ratio = $height_ratio = 1.0;
419 $did_width = $did_height = false;
421 if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
422 $width_ratio = $max_width / $current_width;
426 if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
427 $height_ratio = $max_height / $current_height;
431 // Calculate the larger/smaller ratios
432 $smaller_ratio = min( $width_ratio, $height_ratio );
433 $larger_ratio = max( $width_ratio, $height_ratio );
435 if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
436 // The larger ratio is too big. It would result in an overflow.
437 $ratio = $smaller_ratio;
439 // The larger ratio fits, and is likely to be a more "snug" fit.
440 $ratio = $larger_ratio;
443 // Very small dimensions may result in 0, 1 should be the minimum.
444 $w = max ( 1, (int) round( $current_width * $ratio ) );
445 $h = max ( 1, (int) round( $current_height * $ratio ) );
447 // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
448 // 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.
449 // Thus we look for dimensions that are one pixel shy of the max value and bump them up
451 // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
452 if ( $did_width && $w == $max_width - 1 ) {
453 $w = $max_width; // Round it up
456 // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
457 if ( $did_height && $h == $max_height - 1 ) {
458 $h = $max_height; // Round it up
462 * Filters dimensions to constrain down-sampled images to.
466 * @param array $dimensions The image width and height.
467 * @param int $current_width The current width of the image.
468 * @param int $current_height The current height of the image.
469 * @param int $max_width The maximum width permitted.
470 * @param int $max_height The maximum height permitted.
472 return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
476 * Retrieves calculated resize dimensions for use in WP_Image_Editor.
478 * Calculates dimensions and coordinates for a resized image that fits
479 * within a specified width and height.
481 * Cropping behavior is dependent on the value of $crop:
482 * 1. If false (default), images will not be cropped.
483 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
484 * - x_crop_position accepts 'left' 'center', or 'right'.
485 * - y_crop_position accepts 'top', 'center', or 'bottom'.
486 * Images will be cropped to the specified dimensions within the defined crop area.
487 * 3. If true, images will be cropped to the specified dimensions using center positions.
491 * @param int $orig_w Original width in pixels.
492 * @param int $orig_h Original height in pixels.
493 * @param int $dest_w New width in pixels.
494 * @param int $dest_h New height in pixels.
495 * @param bool|array $crop Optional. Whether to crop image to specified width and height or resize.
496 * An array can specify positioning of the crop area. Default false.
497 * @return false|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
499 function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
501 if ($orig_w <= 0 || $orig_h <= 0)
503 // at least one of dest_w or dest_h must be specific
504 if ($dest_w <= 0 && $dest_h <= 0)
508 * Filters whether to preempt calculating the image resize dimensions.
510 * Passing a non-null value to the filter will effectively short-circuit
511 * image_resize_dimensions(), returning that value instead.
515 * @param null|mixed $null Whether to preempt output of the resize dimensions.
516 * @param int $orig_w Original width in pixels.
517 * @param int $orig_h Original height in pixels.
518 * @param int $dest_w New width in pixels.
519 * @param int $dest_h New height in pixels.
520 * @param bool|array $crop Whether to crop image to specified width and height or resize.
521 * An array can specify positioning of the crop area. Default false.
523 $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
524 if ( null !== $output )
528 // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
529 $aspect_ratio = $orig_w / $orig_h;
530 $new_w = min($dest_w, $orig_w);
531 $new_h = min($dest_h, $orig_h);
534 $new_w = (int) round( $new_h * $aspect_ratio );
538 $new_h = (int) round( $new_w / $aspect_ratio );
541 $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
543 $crop_w = round($new_w / $size_ratio);
544 $crop_h = round($new_h / $size_ratio);
546 if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
547 $crop = array( 'center', 'center' );
550 list( $x, $y ) = $crop;
552 if ( 'left' === $x ) {
554 } elseif ( 'right' === $x ) {
555 $s_x = $orig_w - $crop_w;
557 $s_x = floor( ( $orig_w - $crop_w ) / 2 );
560 if ( 'top' === $y ) {
562 } elseif ( 'bottom' === $y ) {
563 $s_y = $orig_h - $crop_h;
565 $s_y = floor( ( $orig_h - $crop_h ) / 2 );
568 // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
575 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
578 // if the resulting image would be the same size or larger we don't want to resize it
579 if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
583 // the return array matches the parameters to imagecopyresampled()
584 // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
585 return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
590 * Resizes an image to make a thumbnail or intermediate size.
592 * The returned array has the file size, the image width, and image height. The
593 * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the
594 * values of the returned array. The only parameter is the resized file path.
598 * @param string $file File path.
599 * @param int $width Image width.
600 * @param int $height Image height.
601 * @param bool $crop Optional. Whether to crop image to specified width and height or resize.
603 * @return false|array False, if no image was created. Metadata array on success.
605 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
606 if ( $width || $height ) {
607 $editor = wp_get_image_editor( $file );
609 if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
612 $resized_file = $editor->save();
614 if ( ! is_wp_error( $resized_file ) && $resized_file ) {
615 unset( $resized_file['path'] );
616 return $resized_file;
623 * Helper function to test if aspect ratios for two images match.
627 * @param int $source_width Width of the first image in pixels.
628 * @param int $source_height Height of the first image in pixels.
629 * @param int $target_width Width of the second image in pixels.
630 * @param int $target_height Height of the second image in pixels.
631 * @return bool True if aspect ratios match within 1px. False if not.
633 function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
635 * To test for varying crops, we constrain the dimensions of the larger image
636 * to the dimensions of the smaller image and see if they match.
638 if ( $source_width > $target_width ) {
639 $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
640 $expected_size = array( $target_width, $target_height );
642 $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
643 $expected_size = array( $source_width, $source_height );
646 // If the image dimensions are within 1px of the expected size, we consider it a match.
647 $matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 );
653 * Retrieves the image's intermediate size (resized) path, width, and height.
655 * The $size parameter can be an array with the width and height respectively.
656 * If the size matches the 'sizes' metadata array for width and height, then it
657 * will be used. If there is no direct match, then the nearest image size larger
658 * than the specified size will be used. If nothing is found, then the function
659 * will break out and return false.
661 * The metadata 'sizes' is used for compatible sizes that can be used for the
662 * parameter $size value.
664 * The url path will be given, when the $size parameter is a string.
666 * If you are passing an array for the $size, you should consider using
667 * add_image_size() so that a cropped version is generated. It's much more
668 * efficient than having to find the closest-sized image and then having the
669 * browser scale down the image.
673 * @param int $post_id Attachment ID.
674 * @param array|string $size Optional. Image size. Accepts any valid image size, or an array
675 * of width and height values in pixels (in that order).
676 * Default 'thumbnail'.
677 * @return false|array $data {
678 * Array of file relative path, width, and height on success. Additionally includes absolute
679 * path and URL if registered size is passed to $size parameter. False on failure.
681 * @type string $file Image's path relative to uploads directory
682 * @type int $width Width of image
683 * @type int $height Height of image
684 * @type string $path Image's absolute filesystem path.
685 * @type string $url Image's URL.
688 function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
689 if ( ! $size || ! is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) || empty( $imagedata['sizes'] ) ) {
695 // Find the best match when '$size' is an array.
696 if ( is_array( $size ) ) {
697 $candidates = array();
699 if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
700 $imagedata['height'] = $imagedata['sizes']['full']['height'];
701 $imagedata['width'] = $imagedata['sizes']['full']['width'];
704 foreach ( $imagedata['sizes'] as $_size => $data ) {
705 // If there's an exact match to an existing image size, short circuit.
706 if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
707 $candidates[ $data['width'] * $data['height'] ] = $data;
711 // If it's not an exact match, consider larger sizes with the same aspect ratio.
712 if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
713 // If '0' is passed to either size, we test ratios against the original file.
714 if ( 0 === $size[0] || 0 === $size[1] ) {
715 $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
717 $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
721 $candidates[ $data['width'] * $data['height'] ] = $data;
726 if ( ! empty( $candidates ) ) {
727 // Sort the array by size if we have more than one candidate.
728 if ( 1 < count( $candidates ) ) {
729 ksort( $candidates );
732 $data = array_shift( $candidates );
734 * When the size requested is smaller than the thumbnail dimensions, we
735 * fall back to the thumbnail size to maintain backwards compatibility with
736 * pre 4.6 versions of WordPress.
738 } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) && $imagedata['sizes']['thumbnail']['width'] >= $size[0] && $imagedata['sizes']['thumbnail']['width'] >= $size[1] ) {
739 $data = $imagedata['sizes']['thumbnail'];
744 // Constrain the width and height attributes to the requested values.
745 list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
747 } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
748 $data = $imagedata['sizes'][ $size ];
751 // If we still don't have a match at this point, return false.
752 if ( empty( $data ) ) {
756 // include the full filesystem path of the intermediate file
757 if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
758 $file_url = wp_get_attachment_url($post_id);
759 $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
760 $data['url'] = path_join( dirname($file_url), $data['file'] );
764 * Filters the output of image_get_intermediate_size()
768 * @see image_get_intermediate_size()
770 * @param array $data Array of file relative path, width, and height on success. May also include
771 * file absolute path and URL.
772 * @param int $post_id The post_id of the image attachment
773 * @param string|array $size Registered image size or flat array of initially-requested height and width
774 * dimensions (in that order).
776 return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
780 * Gets the available intermediate image sizes.
784 * @return array Returns a filtered array of image size strings.
786 function get_intermediate_image_sizes() {
787 $_wp_additional_image_sizes = wp_get_additional_image_sizes();
788 $image_sizes = array('thumbnail', 'medium', 'medium_large', 'large'); // Standard sizes
789 if ( ! empty( $_wp_additional_image_sizes ) ) {
790 $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
794 * Filters the list of intermediate image sizes.
798 * @param array $image_sizes An array of intermediate image sizes. Defaults
799 * are 'thumbnail', 'medium', 'medium_large', 'large'.
801 return apply_filters( 'intermediate_image_sizes', $image_sizes );
805 * Retrieve an image to represent an attachment.
807 * A mime icon for files, thumbnail or intermediate size for images.
809 * The returned array contains four values: the URL of the attachment image src,
810 * the width of the image file, the height of the image file, and a boolean
811 * representing whether the returned array describes an intermediate (generated)
812 * image size or the original, full-sized upload.
816 * @param int $attachment_id Image attachment ID.
817 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
818 * and height values in pixels (in that order). Default 'thumbnail'.
819 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
820 * @return false|array Returns an array (url, width, height, is_intermediate), or false, if no image is available.
822 function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
823 // get a thumbnail or intermediate image if there is one
824 $image = image_downsize( $attachment_id, $size );
828 if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {
829 /** This filter is documented in wp-includes/post.php */
830 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
832 $src_file = $icon_dir . '/' . wp_basename( $src );
833 @list( $width, $height ) = getimagesize( $src_file );
836 if ( $src && $width && $height ) {
837 $image = array( $src, $width, $height );
841 * Filters the image src result.
845 * @param array|false $image Either array with src, width & height, icon src, or false.
846 * @param int $attachment_id Image attachment ID.
847 * @param string|array $size Size of image. Image size or array of width and height values
848 * (in that order). Default 'thumbnail'.
849 * @param bool $icon Whether the image should be treated as an icon. Default false.
851 return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
855 * Get an HTML img element representing an image attachment
857 * While `$size` will accept an array, it is better to register a size with
858 * add_image_size() so that a cropped version is generated. It's much more
859 * efficient than having to find the closest-sized image and then having the
860 * browser scale down the image.
864 * @param int $attachment_id Image attachment ID.
865 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
866 * and height values in pixels (in that order). Default 'thumbnail'.
867 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
868 * @param string|array $attr Optional. Attributes for the image markup. Default empty.
869 * @return string HTML img element or empty string on failure.
871 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
873 $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
875 list($src, $width, $height) = $image;
876 $hwstring = image_hwstring($width, $height);
878 if ( is_array( $size_class ) ) {
879 $size_class = join( 'x', $size_class );
881 $attachment = get_post($attachment_id);
882 $default_attr = array(
884 'class' => "attachment-$size_class size-$size_class",
885 'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
888 $attr = wp_parse_args( $attr, $default_attr );
890 // Generate 'srcset' and 'sizes' if not already present.
891 if ( empty( $attr['srcset'] ) ) {
892 $image_meta = wp_get_attachment_metadata( $attachment_id );
894 if ( is_array( $image_meta ) ) {
895 $size_array = array( absint( $width ), absint( $height ) );
896 $srcset = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
897 $sizes = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
899 if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
900 $attr['srcset'] = $srcset;
902 if ( empty( $attr['sizes'] ) ) {
903 $attr['sizes'] = $sizes;
910 * Filters the list of attachment image attributes.
914 * @param array $attr Attributes for the image markup.
915 * @param WP_Post $attachment Image attachment post.
916 * @param string|array $size Requested size. Image size or array of width and height values
917 * (in that order). Default 'thumbnail'.
919 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
920 $attr = array_map( 'esc_attr', $attr );
921 $html = rtrim("<img $hwstring");
922 foreach ( $attr as $name => $value ) {
923 $html .= " $name=" . '"' . $value . '"';
932 * Get the URL of an image attachment.
936 * @param int $attachment_id Image attachment ID.
937 * @param string|array $size Optional. Image size to retrieve. Accepts any valid image size, or an array
938 * of width and height values in pixels (in that order). Default 'thumbnail'.
939 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
940 * @return string|false Attachment URL or false if no image is available.
942 function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
943 $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
944 return isset( $image['0'] ) ? $image['0'] : false;
948 * Get the attachment path relative to the upload directory.
953 * @param string $file Attachment file name.
954 * @return string Attachment path relative to the upload directory.
956 function _wp_get_attachment_relative_path( $file ) {
957 $dirname = dirname( $file );
959 if ( '.' === $dirname ) {
963 if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
964 // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads)
965 $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
966 $dirname = ltrim( $dirname, '/' );
973 * Get the image size as array from its meta data.
975 * Used for responsive images.
980 * @param string $size_name Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
981 * @param array $image_meta The image meta data.
982 * @return array|bool Array of width and height values in pixels (in that order)
983 * or false if the size doesn't exist.
985 function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
986 if ( $size_name === 'full' ) {
988 absint( $image_meta['width'] ),
989 absint( $image_meta['height'] ),
991 } elseif ( ! empty( $image_meta['sizes'][$size_name] ) ) {
993 absint( $image_meta['sizes'][$size_name]['width'] ),
994 absint( $image_meta['sizes'][$size_name]['height'] ),
1002 * Retrieves the value for an image attachment's 'srcset' attribute.
1006 * @see wp_calculate_image_srcset()
1008 * @param int $attachment_id Image attachment ID.
1009 * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of
1010 * width and height values in pixels (in that order). Default 'medium'.
1011 * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1013 * @return string|bool A 'srcset' value string or false.
1015 function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
1016 if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
1020 if ( ! is_array( $image_meta ) ) {
1021 $image_meta = wp_get_attachment_metadata( $attachment_id );
1024 $image_src = $image[0];
1025 $size_array = array(
1026 absint( $image[1] ),
1030 return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1034 * A helper function to calculate the image sources to include in a 'srcset' attribute.
1038 * @param array $size_array Array of width and height values in pixels (in that order).
1039 * @param string $image_src The 'src' of the image.
1040 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
1041 * @param int $attachment_id Optional. The image attachment ID to pass to the filter. Default 0.
1042 * @return string|bool The 'srcset' attribute value. False on error or when only one source exists.
1044 function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
1046 * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
1048 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
1049 * @param array $size_array Array of width and height values in pixels (in that order).
1050 * @param string $image_src The 'src' of the image.
1051 * @param int $attachment_id The image attachment ID or 0 if not supplied.
1053 $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
1055 if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
1059 $image_sizes = $image_meta['sizes'];
1061 // Get the width and height of the image.
1062 $image_width = (int) $size_array[0];
1063 $image_height = (int) $size_array[1];
1065 // Bail early if error/no width.
1066 if ( $image_width < 1 ) {
1070 $image_basename = wp_basename( $image_meta['file'] );
1073 * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
1074 * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
1075 * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
1077 if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
1078 $image_sizes[] = array(
1079 'width' => $image_meta['width'],
1080 'height' => $image_meta['height'],
1081 'file' => $image_basename,
1083 } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
1087 // Retrieve the uploads sub-directory from the full size image.
1088 $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1091 $dirname = trailingslashit( $dirname );
1094 $upload_dir = wp_get_upload_dir();
1095 $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
1098 * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
1099 * (which is to say, when they share the domain name of the current request).
1101 if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
1102 $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
1106 * Images that have been edited in WordPress after being uploaded will
1107 * contain a unique hash. Look for that hash and use it later to filter
1108 * out images that are leftovers from previous versions.
1110 $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
1113 * Filters the maximum image width to be included in a 'srcset' attribute.
1117 * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.
1118 * @param array $size_array Array of width and height values in pixels (in that order).
1120 $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
1122 // Array to hold URL candidates.
1126 * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
1127 * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
1128 * an incorrect image. See #35045.
1130 $src_matched = false;
1133 * Loop through available images. Only use images that are resized
1134 * versions of the same edit.
1136 foreach ( $image_sizes as $image ) {
1139 // Check if image meta isn't corrupted.
1140 if ( ! is_array( $image ) ) {
1144 // If the file name is part of the `src`, we've confirmed a match.
1145 if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
1146 $src_matched = $is_src = true;
1149 // Filter out images that are from previous edits.
1150 if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
1155 * Filters out images that are wider than '$max_srcset_image_width' unless
1156 * that file is in the 'src' attribute.
1158 if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
1162 // If the image dimensions are within 1px of the expected size, use it.
1163 if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
1164 // Add the URL, descriptor, and value to the sources array to be returned.
1166 'url' => $image_baseurl . $image['file'],
1167 'descriptor' => 'w',
1168 'value' => $image['width'],
1171 // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
1173 $sources = array( $image['width'] => $source ) + $sources;
1175 $sources[ $image['width'] ] = $source;
1181 * Filters an image's 'srcset' sources.
1185 * @param array $sources {
1186 * One or more arrays of source data to include in the 'srcset'.
1188 * @type array $width {
1189 * @type string $url The URL of an image source.
1190 * @type string $descriptor The descriptor type used in the image candidate string,
1191 * either 'w' or 'x'.
1192 * @type int $value The source width if paired with a 'w' descriptor, or a
1193 * pixel density value if paired with an 'x' descriptor.
1196 * @param array $size_array Array of width and height values in pixels (in that order).
1197 * @param string $image_src The 'src' of the image.
1198 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
1199 * @param int $attachment_id Image attachment ID or 0.
1201 $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
1203 // Only return a 'srcset' value if there is more than one source.
1204 if ( ! $src_matched || count( $sources ) < 2 ) {
1210 foreach ( $sources as $source ) {
1211 $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
1214 return rtrim( $srcset, ', ' );
1218 * Retrieves the value for an image attachment's 'sizes' attribute.
1222 * @see wp_calculate_image_sizes()
1224 * @param int $attachment_id Image attachment ID.
1225 * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of width
1226 * and height values in pixels (in that order). Default 'medium'.
1227 * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1229 * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
1231 function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
1232 if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
1236 if ( ! is_array( $image_meta ) ) {
1237 $image_meta = wp_get_attachment_metadata( $attachment_id );
1240 $image_src = $image[0];
1241 $size_array = array(
1242 absint( $image[1] ),
1246 return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1250 * Creates a 'sizes' attribute value for an image.
1254 * @param array|string $size Image size to retrieve. Accepts any valid image size, or an array
1255 * of width and height values in pixels (in that order). Default 'medium'.
1256 * @param string $image_src Optional. The URL to the image file. Default null.
1257 * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1259 * @param int $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
1260 * is needed when using the image size name as argument for `$size`. Default 0.
1261 * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
1263 function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
1266 if ( is_array( $size ) ) {
1267 $width = absint( $size[0] );
1268 } elseif ( is_string( $size ) ) {
1269 if ( ! $image_meta && $attachment_id ) {
1270 $image_meta = wp_get_attachment_metadata( $attachment_id );
1273 if ( is_array( $image_meta ) ) {
1274 $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
1275 if ( $size_array ) {
1276 $width = absint( $size_array[0] );
1285 // Setup the default 'sizes' attribute.
1286 $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
1289 * Filters the output of 'wp_calculate_image_sizes()'.
1293 * @param string $sizes A source size value for use in a 'sizes' attribute.
1294 * @param array|string $size Requested size. Image size or array of width and height values
1295 * in pixels (in that order).
1296 * @param string|null $image_src The URL to the image file or null.
1297 * @param array|null $image_meta The image meta data as returned by wp_get_attachment_metadata() or null.
1298 * @param int $attachment_id Image attachment ID of the original image or 0.
1300 return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
1304 * Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
1308 * @see wp_image_add_srcset_and_sizes()
1310 * @param string $content The raw post content to be filtered.
1311 * @return string Converted content with 'srcset' and 'sizes' attributes added to images.
1313 function wp_make_content_images_responsive( $content ) {
1314 if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
1318 $selected_images = $attachment_ids = array();
1320 foreach( $matches[0] as $image ) {
1321 if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) &&
1322 ( $attachment_id = absint( $class_id[1] ) ) ) {
1325 * If exactly the same image tag is used more than once, overwrite it.
1326 * All identical tags will be replaced later with 'str_replace()'.
1328 $selected_images[ $image ] = $attachment_id;
1329 // Overwrite the ID when the same image is included more than once.
1330 $attachment_ids[ $attachment_id ] = true;
1334 if ( count( $attachment_ids ) > 1 ) {
1336 * Warm object cache for use with 'get_post_meta()'.
1338 * To avoid making a database call for each image, a single query
1339 * warms the object cache with the meta information for all images.
1341 update_meta_cache( 'post', array_keys( $attachment_ids ) );
1344 foreach ( $selected_images as $image => $attachment_id ) {
1345 $image_meta = wp_get_attachment_metadata( $attachment_id );
1346 $content = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content );
1353 * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
1357 * @see wp_calculate_image_srcset()
1358 * @see wp_calculate_image_sizes()
1360 * @param string $image An HTML 'img' element to be filtered.
1361 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
1362 * @param int $attachment_id Image attachment ID.
1363 * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
1365 function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
1366 // Ensure the image meta exists.
1367 if ( empty( $image_meta['sizes'] ) ) {
1371 $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
1372 list( $image_src ) = explode( '?', $image_src );
1374 // Return early if we couldn't get the image source.
1375 if ( ! $image_src ) {
1379 // Bail early if an image has been inserted and later edited.
1380 if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
1381 strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
1386 $width = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
1387 $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
1389 if ( ! $width || ! $height ) {
1391 * If attempts to parse the size value failed, attempt to use the image meta data to match
1392 * the image file name from 'src' against the available sizes for an attachment.
1394 $image_filename = wp_basename( $image_src );
1396 if ( $image_filename === wp_basename( $image_meta['file'] ) ) {
1397 $width = (int) $image_meta['width'];
1398 $height = (int) $image_meta['height'];
1400 foreach( $image_meta['sizes'] as $image_size_data ) {
1401 if ( $image_filename === $image_size_data['file'] ) {
1402 $width = (int) $image_size_data['width'];
1403 $height = (int) $image_size_data['height'];
1410 if ( ! $width || ! $height ) {
1414 $size_array = array( $width, $height );
1415 $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1418 // Check if there is already a 'sizes' attribute.
1419 $sizes = strpos( $image, ' sizes=' );
1422 $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1426 if ( $srcset && $sizes ) {
1427 // Format the 'srcset' and 'sizes' string and escape attributes.
1428 $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
1430 if ( is_string( $sizes ) ) {
1431 $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
1434 // Add 'srcset' and 'sizes' attributes to the image markup.
1435 $image = preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
1442 * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
1444 * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
1445 * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
1450 * @param array $attr Thumbnail attributes including src, class, alt, title.
1451 * @return array Modified array of attributes including the new 'wp-post-image' class.
1453 function _wp_post_thumbnail_class_filter( $attr ) {
1454 $attr['class'] .= ' wp-post-image';
1459 * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
1460 * filter hook. Internal use only.
1465 * @param array $attr Thumbnail attributes including src, class, alt, title.
1467 function _wp_post_thumbnail_class_filter_add( $attr ) {
1468 add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
1472 * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
1473 * filter hook. Internal use only.
1478 * @param array $attr Thumbnail attributes including src, class, alt, title.
1480 function _wp_post_thumbnail_class_filter_remove( $attr ) {
1481 remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
1484 add_shortcode('wp_caption', 'img_caption_shortcode');
1485 add_shortcode('caption', 'img_caption_shortcode');
1488 * Builds the Caption shortcode output.
1490 * Allows a plugin to replace the content that would otherwise be returned. The
1491 * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr
1492 * parameter and the content parameter values.
1494 * The supported attributes for the shortcode are 'id', 'align', 'width', and
1499 * @param array $attr {
1500 * Attributes of the caption shortcode.
1502 * @type string $id ID of the div element for the caption.
1503 * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
1504 * 'aligncenter', alignright', 'alignnone'.
1505 * @type int $width The width of the caption, in pixels.
1506 * @type string $caption The caption text.
1507 * @type string $class Additional class name(s) added to the caption container.
1509 * @param string $content Shortcode content.
1510 * @return string HTML content to display the caption.
1512 function img_caption_shortcode( $attr, $content = null ) {
1513 // New-style shortcode with the caption inside the shortcode with the link and image tags.
1514 if ( ! isset( $attr['caption'] ) ) {
1515 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
1516 $content = $matches[1];
1517 $attr['caption'] = trim( $matches[2] );
1519 } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
1520 $attr['caption'] = wp_kses( $attr['caption'], 'post' );
1524 * Filters the default caption shortcode output.
1526 * If the filtered output isn't empty, it will be used instead of generating
1527 * the default caption template.
1531 * @see img_caption_shortcode()
1533 * @param string $output The caption output. Default empty.
1534 * @param array $attr Attributes of the caption shortcode.
1535 * @param string $content The image element, possibly wrapped in a hyperlink.
1537 $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
1538 if ( $output != '' )
1541 $atts = shortcode_atts( array(
1543 'align' => 'alignnone',
1547 ), $attr, 'caption' );
1549 $atts['width'] = (int) $atts['width'];
1550 if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
1553 if ( ! empty( $atts['id'] ) )
1554 $atts['id'] = 'id="' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '" ';
1556 $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
1558 $html5 = current_theme_supports( 'html5', 'caption' );
1559 // HTML5 captions never added the extra 10px to the image width
1560 $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
1563 * Filters the width of an image's caption.
1565 * By default, the caption is 10 pixels greater than the width of the image,
1566 * to prevent post content from running up against a floated image.
1570 * @see img_caption_shortcode()
1572 * @param int $width Width of the caption in pixels. To remove this inline style,
1574 * @param array $atts Attributes of the caption shortcode.
1575 * @param string $content The image element, possibly wrapped in a hyperlink.
1577 $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
1580 if ( $caption_width ) {
1581 $style = 'style="width: ' . (int) $caption_width . 'px" ';
1585 $html = '<figure ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
1586 . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
1588 $html = '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
1589 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
1595 add_shortcode('gallery', 'gallery_shortcode');
1598 * Builds the Gallery shortcode output.
1600 * This implements the functionality of the Gallery Shortcode for displaying
1601 * WordPress images on a post.
1605 * @staticvar int $instance
1607 * @param array $attr {
1608 * Attributes of the gallery shortcode.
1610 * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
1611 * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
1612 * Accepts any valid SQL ORDERBY statement.
1613 * @type int $id Post ID.
1614 * @type string $itemtag HTML tag to use for each image in the gallery.
1615 * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
1616 * @type string $icontag HTML tag to use for each image's icon.
1617 * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
1618 * @type string $captiontag HTML tag to use for each image's caption.
1619 * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
1620 * @type int $columns Number of columns of images to display. Default 3.
1621 * @type string|array $size Size of the images to display. Accepts any valid image size, or an array of width
1622 * and height values in pixels (in that order). Default 'thumbnail'.
1623 * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
1624 * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
1625 * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
1626 * @type string $link What to link each image to. Default empty (links to the attachment page).
1627 * Accepts 'file', 'none'.
1629 * @return string HTML content to display gallery.
1631 function gallery_shortcode( $attr ) {
1634 static $instance = 0;
1637 if ( ! empty( $attr['ids'] ) ) {
1638 // 'ids' is explicitly ordered, unless you specify otherwise.
1639 if ( empty( $attr['orderby'] ) ) {
1640 $attr['orderby'] = 'post__in';
1642 $attr['include'] = $attr['ids'];
1646 * Filters the default gallery shortcode output.
1648 * If the filtered output isn't empty, it will be used instead of generating
1649 * the default gallery template.
1652 * @since 4.2.0 The `$instance` parameter was added.
1654 * @see gallery_shortcode()
1656 * @param string $output The gallery output. Default empty.
1657 * @param array $attr Attributes of the gallery shortcode.
1658 * @param int $instance Unique numeric ID of this gallery shortcode instance.
1660 $output = apply_filters( 'post_gallery', '', $attr, $instance );
1661 if ( $output != '' ) {
1665 $html5 = current_theme_supports( 'html5', 'gallery' );
1666 $atts = shortcode_atts( array(
1668 'orderby' => 'menu_order ID',
1669 'id' => $post ? $post->ID : 0,
1670 'itemtag' => $html5 ? 'figure' : 'dl',
1671 'icontag' => $html5 ? 'div' : 'dt',
1672 'captiontag' => $html5 ? 'figcaption' : 'dd',
1674 'size' => 'thumbnail',
1678 ), $attr, 'gallery' );
1680 $id = intval( $atts['id'] );
1682 if ( ! empty( $atts['include'] ) ) {
1683 $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1685 $attachments = array();
1686 foreach ( $_attachments as $key => $val ) {
1687 $attachments[$val->ID] = $_attachments[$key];
1689 } elseif ( ! empty( $atts['exclude'] ) ) {
1690 $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'] ) );
1692 $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1695 if ( empty( $attachments ) ) {
1701 foreach ( $attachments as $att_id => $attachment ) {
1702 $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
1707 $itemtag = tag_escape( $atts['itemtag'] );
1708 $captiontag = tag_escape( $atts['captiontag'] );
1709 $icontag = tag_escape( $atts['icontag'] );
1710 $valid_tags = wp_kses_allowed_html( 'post' );
1711 if ( ! isset( $valid_tags[ $itemtag ] ) ) {
1714 if ( ! isset( $valid_tags[ $captiontag ] ) ) {
1717 if ( ! isset( $valid_tags[ $icontag ] ) ) {
1721 $columns = intval( $atts['columns'] );
1722 $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
1723 $float = is_rtl() ? 'right' : 'left';
1725 $selector = "gallery-{$instance}";
1727 $gallery_style = '';
1730 * Filters whether to print default gallery styles.
1734 * @param bool $print Whether to print default gallery styles.
1735 * Defaults to false if the theme supports HTML5 galleries.
1736 * Otherwise, defaults to true.
1738 if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1740 <style type='text/css'>
1744 #{$selector} .gallery-item {
1748 width: {$itemwidth}%;
1751 border: 2px solid #cfcfcf;
1753 #{$selector} .gallery-caption {
1756 /* see gallery_shortcode() in wp-includes/media.php */
1760 $size_class = sanitize_html_class( $atts['size'] );
1761 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1764 * Filters the default gallery shortcode CSS styles.
1768 * @param string $gallery_style Default CSS styles and opening HTML div container
1769 * for the gallery shortcode output.
1771 $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1774 foreach ( $attachments as $id => $attachment ) {
1776 $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
1777 if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
1778 $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
1779 } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
1780 $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
1782 $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
1784 $image_meta = wp_get_attachment_metadata( $id );
1787 if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
1788 $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1790 $output .= "<{$itemtag} class='gallery-item'>";
1792 <{$icontag} class='gallery-icon {$orientation}'>
1795 if ( $captiontag && trim($attachment->post_excerpt) ) {
1797 <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
1798 " . wptexturize($attachment->post_excerpt) . "
1801 $output .= "</{$itemtag}>";
1802 if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1803 $output .= '<br style="clear: both" />';
1807 if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1809 <br style='clear: both' />";
1819 * Outputs the templates used by playlists.
1823 function wp_underscore_playlist_templates() {
1825 <script type="text/html" id="tmpl-wp-playlist-current-item">
1826 <# if ( data.image ) { #>
1827 <img src="{{ data.thumb.src }}" alt="" />
1829 <div class="wp-playlist-caption">
1830 <span class="wp-playlist-item-meta wp-playlist-item-title"><?php
1831 /* translators: playlist item title */
1832 printf( _x( '“%s”', 'playlist item title' ), '{{ data.title }}' );
1834 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1835 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1838 <script type="text/html" id="tmpl-wp-playlist-item">
1839 <div class="wp-playlist-item">
1840 <a class="wp-playlist-caption" href="{{ data.src }}">
1841 {{ data.index ? ( data.index + '. ' ) : '' }}
1842 <# if ( data.caption ) { #>
1845 <span class="wp-playlist-item-title"><?php
1846 /* translators: playlist item title */
1847 printf( _x( '“%s”', 'playlist item title' ), '{{{ data.title }}}' );
1849 <# if ( data.artists && data.meta.artist ) { #>
1850 <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span>
1854 <# if ( data.meta.length_formatted ) { #>
1855 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1863 * Outputs and enqueue default scripts and styles for playlists.
1867 * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1869 function wp_playlist_scripts( $type ) {
1870 wp_enqueue_style( 'wp-mediaelement' );
1871 wp_enqueue_script( 'wp-playlist' );
1873 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1875 add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1876 add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1880 * Builds the Playlist shortcode output.
1882 * This implements the functionality of the playlist shortcode for displaying
1883 * a collection of WordPress audio or video files in a post.
1887 * @global int $content_width
1888 * @staticvar int $instance
1890 * @param array $attr {
1891 * Array of default playlist attributes.
1893 * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
1894 * @type string $order Designates ascending or descending order of items in the playlist.
1895 * Accepts 'ASC', 'DESC'. Default 'ASC'.
1896 * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
1897 * passed, this defaults to the order of the $ids array ('post__in').
1898 * Otherwise default is 'menu_order ID'.
1899 * @type int $id If an explicit $ids array is not present, this parameter
1900 * will determine which attachments are used for the playlist.
1901 * Default is the current post ID.
1902 * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
1903 * a playlist will be created from all $type attachments of $id.
1905 * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
1906 * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
1907 * @type bool $tracklist Whether to show or hide the playlist. Default true.
1908 * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
1909 * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
1910 * thumbnail). Default true.
1911 * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
1914 * @return string Playlist output. Empty string if the passed type is unsupported.
1916 function wp_playlist_shortcode( $attr ) {
1917 global $content_width;
1920 static $instance = 0;
1923 if ( ! empty( $attr['ids'] ) ) {
1924 // 'ids' is explicitly ordered, unless you specify otherwise.
1925 if ( empty( $attr['orderby'] ) ) {
1926 $attr['orderby'] = 'post__in';
1928 $attr['include'] = $attr['ids'];
1932 * Filters the playlist output.
1934 * Passing a non-empty value to the filter will short-circuit generation
1935 * of the default playlist output, returning the passed value instead.
1938 * @since 4.2.0 The `$instance` parameter was added.
1940 * @param string $output Playlist output. Default empty.
1941 * @param array $attr An array of shortcode attributes.
1942 * @param int $instance Unique numeric ID of this playlist shortcode instance.
1944 $output = apply_filters( 'post_playlist', '', $attr, $instance );
1945 if ( $output != '' ) {
1949 $atts = shortcode_atts( array(
1952 'orderby' => 'menu_order ID',
1953 'id' => $post ? $post->ID : 0,
1957 'tracklist' => true,
1958 'tracknumbers' => true,
1961 ), $attr, 'playlist' );
1963 $id = intval( $atts['id'] );
1965 if ( $atts['type'] !== 'audio' ) {
1966 $atts['type'] = 'video';
1970 'post_status' => 'inherit',
1971 'post_type' => 'attachment',
1972 'post_mime_type' => $atts['type'],
1973 'order' => $atts['order'],
1974 'orderby' => $atts['orderby']
1977 if ( ! empty( $atts['include'] ) ) {
1978 $args['include'] = $atts['include'];
1979 $_attachments = get_posts( $args );
1981 $attachments = array();
1982 foreach ( $_attachments as $key => $val ) {
1983 $attachments[$val->ID] = $_attachments[$key];
1985 } elseif ( ! empty( $atts['exclude'] ) ) {
1986 $args['post_parent'] = $id;
1987 $args['exclude'] = $atts['exclude'];
1988 $attachments = get_children( $args );
1990 $args['post_parent'] = $id;
1991 $attachments = get_children( $args );
1994 if ( empty( $attachments ) ) {
2000 foreach ( $attachments as $att_id => $attachment ) {
2001 $output .= wp_get_attachment_link( $att_id ) . "\n";
2006 $outer = 22; // default padding and border of wrapper
2008 $default_width = 640;
2009 $default_height = 360;
2011 $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
2012 $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
2015 'type' => $atts['type'],
2016 // don't pass strings to JSON, will be truthy in JS
2017 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
2018 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
2019 'images' => wp_validate_boolean( $atts['images'] ),
2020 'artists' => wp_validate_boolean( $atts['artists'] ),
2024 foreach ( $attachments as $attachment ) {
2025 $url = wp_get_attachment_url( $attachment->ID );
2026 $ftype = wp_check_filetype( $url, wp_get_mime_types() );
2029 'type' => $ftype['type'],
2030 'title' => $attachment->post_title,
2031 'caption' => $attachment->post_excerpt,
2032 'description' => $attachment->post_content
2035 $track['meta'] = array();
2036 $meta = wp_get_attachment_metadata( $attachment->ID );
2037 if ( ! empty( $meta ) ) {
2039 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
2040 if ( ! empty( $meta[ $key ] ) ) {
2041 $track['meta'][ $key ] = $meta[ $key ];
2045 if ( 'video' === $atts['type'] ) {
2046 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
2047 $width = $meta['width'];
2048 $height = $meta['height'];
2049 $theme_height = round( ( $height * $theme_width ) / $width );
2051 $width = $default_width;
2052 $height = $default_height;
2055 $track['dimensions'] = array(
2056 'original' => compact( 'width', 'height' ),
2058 'width' => $theme_width,
2059 'height' => $theme_height
2065 if ( $atts['images'] ) {
2066 $thumb_id = get_post_thumbnail_id( $attachment->ID );
2067 if ( ! empty( $thumb_id ) ) {
2068 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
2069 $track['image'] = compact( 'src', 'width', 'height' );
2070 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
2071 $track['thumb'] = compact( 'src', 'width', 'height' );
2073 $src = wp_mime_type_icon( $attachment->ID );
2076 $track['image'] = compact( 'src', 'width', 'height' );
2077 $track['thumb'] = compact( 'src', 'width', 'height' );
2083 $data['tracks'] = $tracks;
2085 $safe_type = esc_attr( $atts['type'] );
2086 $safe_style = esc_attr( $atts['style'] );
2090 if ( 1 === $instance ) {
2092 * Prints and enqueues playlist scripts, styles, and JavaScript templates.
2096 * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
2097 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
2099 do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
2101 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
2102 <?php if ( 'audio' === $atts['type'] ): ?>
2103 <div class="wp-playlist-current-item"></div>
2105 <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
2106 echo (int) $theme_width;
2107 ?>"<?php if ( 'video' === $safe_type ):
2108 echo ' height="', (int) $theme_height, '"';
2109 endif; ?>></<?php echo $safe_type ?>>
2110 <div class="wp-playlist-next"></div>
2111 <div class="wp-playlist-prev"></div>
2114 foreach ( $attachments as $att_id => $attachment ) {
2115 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
2119 <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
2122 return ob_get_clean();
2124 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
2127 * Provides a No-JS Flash fallback as a last resort for audio / video.
2131 * @param string $url The media element URL.
2132 * @return string Fallback HTML.
2134 function wp_mediaelement_fallback( $url ) {
2136 * Filters the Mediaelement fallback output for no-JS.
2140 * @param string $output Fallback output for no-JS.
2141 * @param string $url Media file URL.
2143 return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
2147 * Returns a filtered list of WP-supported audio formats.
2151 * @return array Supported audio formats.
2153 function wp_get_audio_extensions() {
2155 * Filters the list of supported audio formats.
2159 * @param array $extensions An array of support audio formats. Defaults are
2160 * 'mp3', 'ogg', 'wma', 'm4a', 'wav'.
2162 return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
2166 * Returns useful keys to use to lookup data from an attachment's stored metadata.
2170 * @param WP_Post $attachment The current attachment, provided for context.
2171 * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'.
2172 * @return array Key/value pairs of field keys to labels.
2174 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
2176 'artist' => __( 'Artist' ),
2177 'album' => __( 'Album' ),
2180 if ( 'display' === $context ) {
2181 $fields['genre'] = __( 'Genre' );
2182 $fields['year'] = __( 'Year' );
2183 $fields['length_formatted'] = _x( 'Length', 'video or audio' );
2184 } elseif ( 'js' === $context ) {
2185 $fields['bitrate'] = __( 'Bitrate' );
2186 $fields['bitrate_mode'] = __( 'Bitrate Mode' );
2190 * Filters the editable list of keys to look up data from an attachment's metadata.
2194 * @param array $fields Key/value pairs of field keys to labels.
2195 * @param WP_Post $attachment Attachment object.
2196 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
2198 return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
2201 * Builds the Audio shortcode output.
2203 * This implements the functionality of the Audio Shortcode for displaying
2204 * WordPress mp3s in a post.
2208 * @staticvar int $instance
2210 * @param array $attr {
2211 * Attributes of the audio shortcode.
2213 * @type string $src URL to the source of the audio file. Default empty.
2214 * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
2215 * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
2216 * @type string $preload The 'preload' attribute for the `<audio>` element. Default 'none'.
2217 * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
2218 * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%;'.
2220 * @param string $content Shortcode content.
2221 * @return string|void HTML content to display audio.
2223 function wp_audio_shortcode( $attr, $content = '' ) {
2224 $post_id = get_post() ? get_the_ID() : 0;
2226 static $instance = 0;
2230 * Filters the default audio shortcode output.
2232 * If the filtered output isn't empty, it will be used instead of generating the default audio template.
2236 * @param string $html Empty variable to be replaced with shortcode markup.
2237 * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
2238 * @param string $content Shortcode content.
2239 * @param int $instance Unique numeric ID of this audio shortcode instance.
2241 $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
2242 if ( '' !== $override ) {
2248 $default_types = wp_get_audio_extensions();
2249 $defaults_atts = array(
2253 'preload' => 'none',
2254 'class' => 'wp-audio-shortcode',
2255 'style' => 'width: 100%;'
2257 foreach ( $default_types as $type ) {
2258 $defaults_atts[$type] = '';
2261 $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
2264 if ( ! empty( $atts['src'] ) ) {
2265 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2266 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
2267 return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2270 array_unshift( $default_types, 'src' );
2272 foreach ( $default_types as $ext ) {
2273 if ( ! empty( $atts[ $ext ] ) ) {
2274 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2275 if ( strtolower( $type['ext'] ) === $ext ) {
2283 $audios = get_attached_media( 'audio', $post_id );
2284 if ( empty( $audios ) ) {
2288 $audio = reset( $audios );
2289 $atts['src'] = wp_get_attachment_url( $audio->ID );
2290 if ( empty( $atts['src'] ) ) {
2294 array_unshift( $default_types, 'src' );
2298 * Filters the media library used for the audio shortcode.
2302 * @param string $library Media library used for the audio shortcode.
2304 $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
2305 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
2306 wp_enqueue_style( 'wp-mediaelement' );
2307 wp_enqueue_script( 'wp-mediaelement' );
2311 * Filters the class attribute for the audio shortcode output container.
2315 * @param string $class CSS class or list of space-separated classes.
2317 $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'] );
2320 'class' => $atts['class'],
2321 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
2322 'loop' => wp_validate_boolean( $atts['loop'] ),
2323 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
2324 'preload' => $atts['preload'],
2325 'style' => $atts['style'],
2328 // These ones should just be omitted altogether if they are blank
2329 foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
2330 if ( empty( $html_atts[$a] ) ) {
2331 unset( $html_atts[$a] );
2335 $attr_strings = array();
2336 foreach ( $html_atts as $k => $v ) {
2337 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
2341 if ( 'mediaelement' === $library && 1 === $instance ) {
2342 $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
2344 $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
2347 $source = '<source type="%s" src="%s" />';
2348 foreach ( $default_types as $fallback ) {
2349 if ( ! empty( $atts[ $fallback ] ) ) {
2350 if ( empty( $fileurl ) ) {
2351 $fileurl = $atts[ $fallback ];
2353 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
2354 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
2355 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
2359 if ( 'mediaelement' === $library ) {
2360 $html .= wp_mediaelement_fallback( $fileurl );
2362 $html .= '</audio>';
2365 * Filters the audio shortcode output.
2369 * @param string $html Audio shortcode HTML output.
2370 * @param array $atts Array of audio shortcode attributes.
2371 * @param string $audio Audio file.
2372 * @param int $post_id Post ID.
2373 * @param string $library Media library used for the audio shortcode.
2375 return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
2377 add_shortcode( 'audio', 'wp_audio_shortcode' );
2380 * Returns a filtered list of WP-supported video formats.
2384 * @return array List of supported video formats.
2386 function wp_get_video_extensions() {
2388 * Filters the list of supported video formats.
2392 * @param array $extensions An array of support video formats. Defaults are
2393 * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
2395 return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
2399 * Builds the Video shortcode output.
2401 * This implements the functionality of the Video Shortcode for displaying
2402 * WordPress mp4s in a post.
2406 * @global int $content_width
2407 * @staticvar int $instance
2409 * @param array $attr {
2410 * Attributes of the shortcode.
2412 * @type string $src URL to the source of the video file. Default empty.
2413 * @type int $height Height of the video embed in pixels. Default 360.
2414 * @type int $width Width of the video embed in pixels. Default $content_width or 640.
2415 * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
2416 * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
2417 * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
2418 * @type string $preload The 'preload' attribute for the `<video>` element.
2419 * Default 'metadata'.
2420 * @type string $class The 'class' attribute for the `<video>` element.
2421 * Default 'wp-video-shortcode'.
2423 * @param string $content Shortcode content.
2424 * @return string|void HTML content to display video.
2426 function wp_video_shortcode( $attr, $content = '' ) {
2427 global $content_width;
2428 $post_id = get_post() ? get_the_ID() : 0;
2430 static $instance = 0;
2434 * Filters the default video shortcode output.
2436 * If the filtered output isn't empty, it will be used instead of generating
2437 * the default video template.
2441 * @see wp_video_shortcode()
2443 * @param string $html Empty variable to be replaced with shortcode markup.
2444 * @param array $attr Attributes of the video shortcode.
2445 * @param string $content Video shortcode content.
2446 * @param int $instance Unique numeric ID of this video shortcode instance.
2448 $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
2449 if ( '' !== $override ) {
2455 $default_types = wp_get_video_extensions();
2456 $defaults_atts = array(
2461 'preload' => 'metadata',
2464 'class' => 'wp-video-shortcode',
2467 foreach ( $default_types as $type ) {
2468 $defaults_atts[$type] = '';
2471 $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
2474 // shrink the video so it isn't huge in the admin
2475 if ( $atts['width'] > $defaults_atts['width'] ) {
2476 $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
2477 $atts['width'] = $defaults_atts['width'];
2480 // if the video is bigger than the theme
2481 if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
2482 $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
2483 $atts['width'] = $content_width;
2487 $is_vimeo = $is_youtube = false;
2488 $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
2489 $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
2492 if ( ! empty( $atts['src'] ) ) {
2493 $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
2494 $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
2495 if ( ! $is_youtube && ! $is_vimeo ) {
2496 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2497 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
2498 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2503 wp_enqueue_script( 'froogaloop' );
2507 array_unshift( $default_types, 'src' );
2509 foreach ( $default_types as $ext ) {
2510 if ( ! empty( $atts[ $ext ] ) ) {
2511 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2512 if ( strtolower( $type['ext'] ) === $ext ) {
2520 $videos = get_attached_media( 'video', $post_id );
2521 if ( empty( $videos ) ) {
2525 $video = reset( $videos );
2526 $atts['src'] = wp_get_attachment_url( $video->ID );
2527 if ( empty( $atts['src'] ) ) {
2531 array_unshift( $default_types, 'src' );
2535 * Filters the media library used for the video shortcode.
2539 * @param string $library Media library used for the video shortcode.
2541 $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
2542 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
2543 wp_enqueue_style( 'wp-mediaelement' );
2544 wp_enqueue_script( 'wp-mediaelement' );
2548 * Filters the class attribute for the video shortcode output container.
2552 * @param string $class CSS class or list of space-separated classes.
2554 $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'] );
2557 'class' => $atts['class'],
2558 'id' => sprintf( 'video-%d-%d', $post_id, $instance ),
2559 'width' => absint( $atts['width'] ),
2560 'height' => absint( $atts['height'] ),
2561 'poster' => esc_url( $atts['poster'] ),
2562 'loop' => wp_validate_boolean( $atts['loop'] ),
2563 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
2564 'preload' => $atts['preload'],
2567 // These ones should just be omitted altogether if they are blank
2568 foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
2569 if ( empty( $html_atts[$a] ) ) {
2570 unset( $html_atts[$a] );
2574 $attr_strings = array();
2575 foreach ( $html_atts as $k => $v ) {
2576 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
2580 if ( 'mediaelement' === $library && 1 === $instance ) {
2581 $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
2583 $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
2586 $source = '<source type="%s" src="%s" />';
2587 foreach ( $default_types as $fallback ) {
2588 if ( ! empty( $atts[ $fallback ] ) ) {
2589 if ( empty( $fileurl ) ) {
2590 $fileurl = $atts[ $fallback ];
2592 if ( 'src' === $fallback && $is_youtube ) {
2593 $type = array( 'type' => 'video/youtube' );
2594 } elseif ( 'src' === $fallback && $is_vimeo ) {
2595 $type = array( 'type' => 'video/vimeo' );
2597 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
2599 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
2600 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
2604 if ( ! empty( $content ) ) {
2605 if ( false !== strpos( $content, "\n" ) ) {
2606 $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
2608 $html .= trim( $content );
2611 if ( 'mediaelement' === $library ) {
2612 $html .= wp_mediaelement_fallback( $fileurl );
2614 $html .= '</video>';
2617 if ( ! empty( $atts['width'] ) ) {
2618 $width_rule = sprintf( 'width: %dpx;', $atts['width'] );
2620 $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
2623 * Filters the output of the video shortcode.
2627 * @param string $output Video shortcode HTML output.
2628 * @param array $atts Array of video shortcode attributes.
2629 * @param string $video Video file.
2630 * @param int $post_id Post ID.
2631 * @param string $library Media library used for the video shortcode.
2633 return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
2635 add_shortcode( 'video', 'wp_video_shortcode' );
2638 * Displays previous image link that has the same post parent.
2642 * @see adjacent_image_link()
2644 * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
2645 * height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
2646 * default to 'post_title' or `$text`. Default 'thumbnail'.
2647 * @param string $text Optional. Link text. Default false.
2649 function previous_image_link( $size = 'thumbnail', $text = false ) {
2650 adjacent_image_link(true, $size, $text);
2654 * Displays next image link that has the same post parent.
2658 * @see adjacent_image_link()
2660 * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
2661 * height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
2662 * default to 'post_title' or `$text`. Default 'thumbnail'.
2663 * @param string $text Optional. Link text. Default false.
2665 function next_image_link( $size = 'thumbnail', $text = false ) {
2666 adjacent_image_link(false, $size, $text);
2670 * Displays next or previous image link that has the same post parent.
2672 * Retrieves the current attachment object from the $post global.
2676 * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
2677 * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width and height
2678 * values in pixels (in that order). Default 'thumbnail'.
2679 * @param bool $text Optional. Link text. Default false.
2681 function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
2683 $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' ) ) );
2685 foreach ( $attachments as $k => $attachment ) {
2686 if ( $attachment->ID == $post->ID ) {
2694 if ( $attachments ) {
2695 $k = $prev ? $k - 1 : $k + 1;
2697 if ( isset( $attachments[ $k ] ) ) {
2698 $attachment_id = $attachments[ $k ]->ID;
2699 $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
2703 $adjacent = $prev ? 'previous' : 'next';
2706 * Filters the adjacent image link.
2708 * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
2709 * either 'next', or 'previous'.
2713 * @param string $output Adjacent image HTML markup.
2714 * @param int $attachment_id Attachment ID
2715 * @param string $size Image size.
2716 * @param string $text Link text.
2718 echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
2722 * Retrieves taxonomies attached to given the attachment.
2725 * @since 4.7.0 Introduced the `$output` parameter.
2727 * @param int|array|object $attachment Attachment ID, data array, or data object.
2728 * @param string $output Output type. 'names' to return an array of taxonomy names,
2729 * or 'objects' to return an array of taxonomy objects.
2730 * Default is 'names'.
2731 * @return array Empty array on failure. List of taxonomies on success.
2733 function get_attachment_taxonomies( $attachment, $output = 'names' ) {
2734 if ( is_int( $attachment ) ) {
2735 $attachment = get_post( $attachment );
2736 } elseif ( is_array( $attachment ) ) {
2737 $attachment = (object) $attachment;
2739 if ( ! is_object($attachment) )
2742 $file = get_attached_file( $attachment->ID );
2743 $filename = basename( $file );
2745 $objects = array('attachment');
2747 if ( false !== strpos($filename, '.') )
2748 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
2749 if ( !empty($attachment->post_mime_type) ) {
2750 $objects[] = 'attachment:' . $attachment->post_mime_type;
2751 if ( false !== strpos($attachment->post_mime_type, '/') )
2752 foreach ( explode('/', $attachment->post_mime_type) as $token )
2753 if ( !empty($token) )
2754 $objects[] = "attachment:$token";
2757 $taxonomies = array();
2758 foreach ( $objects as $object ) {
2759 if ( $taxes = get_object_taxonomies( $object, $output ) ) {
2760 $taxonomies = array_merge( $taxonomies, $taxes );
2764 if ( 'names' === $output ) {
2765 $taxonomies = array_unique( $taxonomies );
2772 * Retrieves all of the taxonomy names that are registered for attachments.
2774 * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
2778 * @see get_taxonomies()
2780 * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
2782 * @return array The names of all taxonomy of $object_type.
2784 function get_taxonomies_for_attachments( $output = 'names' ) {
2785 $taxonomies = array();
2786 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
2787 foreach ( $taxonomy->object_type as $object_type ) {
2788 if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
2789 if ( 'names' == $output )
2790 $taxonomies[] = $taxonomy->name;
2792 $taxonomies[ $taxonomy->name ] = $taxonomy;
2802 * Create new GD image resource with transparency support
2804 * @todo: Deprecate if possible.
2808 * @param int $width Image width in pixels.
2809 * @param int $height Image height in pixels..
2810 * @return resource The GD image resource.
2812 function wp_imagecreatetruecolor($width, $height) {
2813 $img = imagecreatetruecolor($width, $height);
2814 if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
2815 imagealphablending($img, false);
2816 imagesavealpha($img, true);
2822 * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
2826 * @see wp_constrain_dimensions()
2828 * @param int $example_width The width of an example embed.
2829 * @param int $example_height The height of an example embed.
2830 * @param int $max_width The maximum allowed width.
2831 * @param int $max_height The maximum allowed height.
2832 * @return array The maximum possible width and height based on the example ratio.
2834 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
2835 $example_width = (int) $example_width;
2836 $example_height = (int) $example_height;
2837 $max_width = (int) $max_width;
2838 $max_height = (int) $max_height;
2840 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
2844 * Determines the maximum upload size allowed in php.ini.
2848 * @return int Allowed upload size.
2850 function wp_max_upload_size() {
2851 $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2852 $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2855 * Filters the maximum upload size allowed in php.ini.
2859 * @param int $size Max upload size limit in bytes.
2860 * @param int $u_bytes Maximum upload filesize in bytes.
2861 * @param int $p_bytes Maximum size of POST data in bytes.
2863 return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2867 * Returns a WP_Image_Editor instance and loads file into it.
2871 * @param string $path Path to the file to load.
2872 * @param array $args Optional. Additional arguments for retrieving the image editor.
2873 * Default empty array.
2874 * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
2877 function wp_get_image_editor( $path, $args = array() ) {
2878 $args['path'] = $path;
2880 if ( ! isset( $args['mime_type'] ) ) {
2881 $file_info = wp_check_filetype( $args['path'] );
2883 // If $file_info['type'] is false, then we let the editor attempt to
2884 // figure out the file type, rather than forcing a failure based on extension.
2885 if ( isset( $file_info ) && $file_info['type'] )
2886 $args['mime_type'] = $file_info['type'];
2889 $implementation = _wp_image_editor_choose( $args );
2891 if ( $implementation ) {
2892 $editor = new $implementation( $path );
2893 $loaded = $editor->load();
2895 if ( is_wp_error( $loaded ) )
2901 return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
2905 * Tests whether there is an editor that supports a given mime type or methods.
2909 * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
2910 * Default empty array.
2911 * @return bool True if an eligible editor is found; false otherwise.
2913 function wp_image_editor_supports( $args = array() ) {
2914 return (bool) _wp_image_editor_choose( $args );
2918 * Tests which editors are capable of supporting the request.
2923 * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
2924 * @return string|false Class name for the first editor that claims to support the request. False if no
2925 * editor claims to support the request.
2927 function _wp_image_editor_choose( $args = array() ) {
2928 require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
2929 require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
2930 require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
2932 * Filters the list of image editing library classes.
2936 * @param array $image_editors List of available image editors. Defaults are
2937 * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
2939 $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
2941 foreach ( $implementations as $implementation ) {
2942 if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
2945 if ( isset( $args['mime_type'] ) &&
2947 array( $implementation, 'supports_mime_type' ),
2948 $args['mime_type'] ) ) {
2952 if ( isset( $args['methods'] ) &&
2953 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
2957 return $implementation;
2964 * Prints default Plupload arguments.
2968 function wp_plupload_default_settings() {
2969 $wp_scripts = wp_scripts();
2971 $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
2972 if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
2975 $max_upload_size = wp_max_upload_size();
2976 $allowed_extensions = array_keys( get_allowed_mime_types() );
2977 $extensions = array();
2978 foreach ( $allowed_extensions as $extension ) {
2979 $extensions = array_merge( $extensions, explode( '|', $extension ) );
2983 'runtimes' => 'html5,flash,silverlight,html4',
2984 'file_data_name' => 'async-upload', // key passed to $_FILE.
2985 'url' => admin_url( 'async-upload.php', 'relative' ),
2986 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
2987 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
2989 'max_file_size' => $max_upload_size . 'b',
2990 'mime_types' => array( array( 'extensions' => implode( ',', $extensions ) ) ),
2994 // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
2995 // when enabled. See #29602.
2996 if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
2997 strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
2999 $defaults['multi_selection'] = false;
3003 * Filters the Plupload default settings.
3007 * @param array $defaults Default Plupload settings array.
3009 $defaults = apply_filters( 'plupload_default_settings', $defaults );
3012 'action' => 'upload-attachment',
3016 * Filters the Plupload default parameters.
3020 * @param array $params Default Plupload parameters array.
3022 $params = apply_filters( 'plupload_default_params', $params );
3023 $params['_wpnonce'] = wp_create_nonce( 'media-form' );
3024 $defaults['multipart_params'] = $params;
3027 'defaults' => $defaults,
3029 'mobile' => wp_is_mobile(),
3030 'supported' => _device_can_upload(),
3032 'limitExceeded' => is_multisite() && ! is_upload_space_available()
3035 $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
3038 $script = "$data\n$script";
3040 $wp_scripts->add_data( 'wp-plupload', 'data', $script );
3044 * Prepares an attachment post object for JS, where it is expected
3045 * to be JSON-encoded and fit into an Attachment model.
3049 * @param mixed $attachment Attachment ID or object.
3050 * @return array|void Array of attachment details.
3052 function wp_prepare_attachment_for_js( $attachment ) {
3053 if ( ! $attachment = get_post( $attachment ) )
3056 if ( 'attachment' != $attachment->post_type )
3059 $meta = wp_get_attachment_metadata( $attachment->ID );
3060 if ( false !== strpos( $attachment->post_mime_type, '/' ) )
3061 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
3063 list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
3065 $attachment_url = wp_get_attachment_url( $attachment->ID );
3066 $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
3069 'id' => $attachment->ID,
3070 'title' => $attachment->post_title,
3071 'filename' => wp_basename( get_attached_file( $attachment->ID ) ),
3072 'url' => $attachment_url,
3073 'link' => get_attachment_link( $attachment->ID ),
3074 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
3075 'author' => $attachment->post_author,
3076 'description' => $attachment->post_content,
3077 'caption' => $attachment->post_excerpt,
3078 'name' => $attachment->post_name,
3079 'status' => $attachment->post_status,
3080 'uploadedTo' => $attachment->post_parent,
3081 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
3082 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
3083 'menuOrder' => $attachment->menu_order,
3084 'mime' => $attachment->post_mime_type,
3086 'subtype' => $subtype,
3087 'icon' => wp_mime_type_icon( $attachment->ID ),
3088 'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
3094 'editLink' => false,
3098 $author = new WP_User( $attachment->post_author );
3099 $response['authorName'] = $author->display_name;
3101 if ( $attachment->post_parent ) {
3102 $post_parent = get_post( $attachment->post_parent );
3104 $post_parent = false;
3107 if ( $post_parent ) {
3108 $parent_type = get_post_type_object( $post_parent->post_type );
3110 if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
3111 $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
3114 if ( $parent_type && current_user_can( 'read_post', $attachment->post_parent ) ) {
3115 $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
3119 $attached_file = get_attached_file( $attachment->ID );
3121 if ( isset( $meta['filesize'] ) ) {
3122 $bytes = $meta['filesize'];
3123 } elseif ( file_exists( $attached_file ) ) {
3124 $bytes = filesize( $attached_file );
3130 $response['filesizeInBytes'] = $bytes;
3131 $response['filesizeHumanReadable'] = size_format( $bytes );
3134 if ( current_user_can( 'edit_post', $attachment->ID ) ) {
3135 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
3136 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
3137 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
3140 if ( current_user_can( 'delete_post', $attachment->ID ) )
3141 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
3143 if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) {
3146 /** This filter is documented in wp-admin/includes/media.php */
3147 $possible_sizes = apply_filters( 'image_size_names_choose', array(
3148 'thumbnail' => __('Thumbnail'),
3149 'medium' => __('Medium'),
3150 'large' => __('Large'),
3151 'full' => __('Full Size'),
3153 unset( $possible_sizes['full'] );
3155 // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
3156 // First: run the image_downsize filter. If it returns something, we can use its data.
3157 // If the filter does not return something, then image_downsize() is just an expensive
3158 // way to check the image metadata, which we do second.
3159 foreach ( $possible_sizes as $size => $label ) {
3161 /** This filter is documented in wp-includes/media.php */
3162 if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
3163 if ( empty( $downsize[3] ) ) {
3167 $sizes[ $size ] = array(
3168 'height' => $downsize[2],
3169 'width' => $downsize[1],
3170 'url' => $downsize[0],
3171 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
3173 } elseif ( isset( $meta['sizes'][ $size ] ) ) {
3174 // Nothing from the filter, so consult image metadata if we have it.
3175 $size_meta = $meta['sizes'][ $size ];
3177 // We have the actual image size, but might need to further constrain it if content_width is narrower.
3178 // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
3179 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
3181 $sizes[ $size ] = array(
3182 'height' => $height,
3184 'url' => $base_url . $size_meta['file'],
3185 'orientation' => $height > $width ? 'portrait' : 'landscape',
3190 if ( 'image' === $type ) {
3191 $sizes['full'] = array( 'url' => $attachment_url );
3193 if ( isset( $meta['height'], $meta['width'] ) ) {
3194 $sizes['full']['height'] = $meta['height'];
3195 $sizes['full']['width'] = $meta['width'];
3196 $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
3199 $response = array_merge( $response, $sizes['full'] );
3200 } elseif ( $meta['sizes']['full']['file'] ) {
3201 $sizes['full'] = array(
3202 'url' => $base_url . $meta['sizes']['full']['file'],
3203 'height' => $meta['sizes']['full']['height'],
3204 'width' => $meta['sizes']['full']['width'],
3205 'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape'
3209 $response = array_merge( $response, array( 'sizes' => $sizes ) );
3212 if ( $meta && 'video' === $type ) {
3213 if ( isset( $meta['width'] ) )
3214 $response['width'] = (int) $meta['width'];
3215 if ( isset( $meta['height'] ) )
3216 $response['height'] = (int) $meta['height'];
3219 if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
3220 if ( isset( $meta['length_formatted'] ) )
3221 $response['fileLength'] = $meta['length_formatted'];
3223 $response['meta'] = array();
3224 foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
3225 $response['meta'][ $key ] = false;
3227 if ( ! empty( $meta[ $key ] ) ) {
3228 $response['meta'][ $key ] = $meta[ $key ];
3232 $id = get_post_thumbnail_id( $attachment->ID );
3233 if ( ! empty( $id ) ) {
3234 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
3235 $response['image'] = compact( 'src', 'width', 'height' );
3236 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
3237 $response['thumb'] = compact( 'src', 'width', 'height' );
3239 $src = wp_mime_type_icon( $attachment->ID );
3242 $response['image'] = compact( 'src', 'width', 'height' );
3243 $response['thumb'] = compact( 'src', 'width', 'height' );
3247 if ( function_exists('get_compat_media_markup') )
3248 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
3251 * Filters the attachment data prepared for JavaScript.
3255 * @param array $response Array of prepared attachment data.
3256 * @param int|object $attachment Attachment ID or object.
3257 * @param array $meta Array of attachment meta data.
3259 return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
3263 * Enqueues all scripts, styles, settings, and templates necessary to use
3264 * all media JS APIs.
3268 * @global int $content_width
3269 * @global wpdb $wpdb
3270 * @global WP_Locale $wp_locale
3272 * @param array $args {
3273 * Arguments for enqueuing media scripts.
3275 * @type int|WP_Post A post object or ID.
3278 function wp_enqueue_media( $args = array() ) {
3279 // Enqueue me just once per page, please.
3280 if ( did_action( 'wp_enqueue_media' ) )
3283 global $content_width, $wpdb, $wp_locale;
3288 $args = wp_parse_args( $args, $defaults );
3290 // We're going to pass the old thickbox media tabs to `media_upload_tabs`
3291 // to ensure plugins will work. We will then unset those tabs.
3293 // handler action suffix => tab label
3300 /** This filter is documented in wp-admin/includes/media.php */
3301 $tabs = apply_filters( 'media_upload_tabs', $tabs );
3302 unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
3305 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
3306 'align' => get_option( 'image_default_align' ), // empty default
3307 'size' => get_option( 'image_default_size' ), // empty default
3310 $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
3311 $mimes = get_allowed_mime_types();
3312 $ext_mimes = array();
3313 foreach ( $exts as $ext ) {
3314 foreach ( $mimes as $ext_preg => $mime_match ) {
3315 if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
3316 $ext_mimes[ $ext ] = $mime_match;
3322 $has_audio = $wpdb->get_var( "
3325 WHERE post_type = 'attachment'
3326 AND post_mime_type LIKE 'audio%'
3329 $has_video = $wpdb->get_var( "
3332 WHERE post_type = 'attachment'
3333 AND post_mime_type LIKE 'video%'
3336 $months = $wpdb->get_results( $wpdb->prepare( "
3337 SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
3339 WHERE post_type = %s
3340 ORDER BY post_date DESC
3341 ", 'attachment' ) );
3342 foreach ( $months as $month_year ) {
3343 $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
3348 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
3349 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
3350 /** This filter is documented in wp-admin/includes/media.php */
3351 'captions' => ! apply_filters( 'disable_captions', '' ),
3353 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
3358 'defaultProps' => $props,
3359 'attachmentCounts' => array(
3360 'audio' => ( $has_audio ) ? 1 : 0,
3361 'video' => ( $has_video ) ? 1 : 0
3363 'embedExts' => $exts,
3364 'embedMimes' => $ext_mimes,
3365 'contentWidth' => $content_width,
3366 'months' => $months,
3367 'mediaTrash' => MEDIA_TRASH ? 1 : 0
3371 if ( isset( $args['post'] ) ) {
3372 $post = get_post( $args['post'] );
3373 $settings['post'] = array(
3375 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
3378 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
3379 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
3380 if ( wp_attachment_is( 'audio', $post ) ) {
3381 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
3382 } elseif ( wp_attachment_is( 'video', $post ) ) {
3383 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
3387 if ( $thumbnail_support ) {
3388 $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
3389 $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
3394 $post_type_object = get_post_type_object( $post->post_type );
3396 $post_type_object = get_post_type_object( 'post' );
3401 'url' => __( 'URL' ),
3402 'addMedia' => __( 'Add Media' ),
3403 'search' => __( 'Search' ),
3404 'select' => __( 'Select' ),
3405 'cancel' => __( 'Cancel' ),
3406 'update' => __( 'Update' ),
3407 'replace' => __( 'Replace' ),
3408 'remove' => __( 'Remove' ),
3409 'back' => __( 'Back' ),
3410 /* translators: This is a would-be plural string used in the media manager.
3411 If there is not a word you can use in your language to avoid issues with the
3412 lack of plural support here, turn it into "selected: %d" then translate it.
3414 'selected' => __( '%d selected' ),
3415 'dragInfo' => __( 'Drag and drop to reorder media files.' ),
3418 'uploadFilesTitle' => __( 'Upload Files' ),
3419 'uploadImagesTitle' => __( 'Upload Images' ),
3422 'mediaLibraryTitle' => __( 'Media Library' ),
3423 'insertMediaTitle' => __( 'Insert Media' ),
3424 'createNewGallery' => __( 'Create a new gallery' ),
3425 'createNewPlaylist' => __( 'Create a new playlist' ),
3426 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
3427 'returnToLibrary' => __( '← Return to library' ),
3428 'allMediaItems' => __( 'All media items' ),
3429 'allDates' => __( 'All dates' ),
3430 'noItemsFound' => __( 'No items found.' ),
3431 'insertIntoPost' => $post_type_object->labels->insert_into_item,
3432 'unattached' => __( 'Unattached' ),
3433 'trash' => _x( 'Trash', 'noun' ),
3434 'uploadedToThisPost' => $post_type_object->labels->uploaded_to_this_item,
3435 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
3436 'warnBulkDelete' => __( "You are about to permanently delete these items.\n 'Cancel' to stop, 'OK' to delete." ),
3437 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
3438 'bulkSelect' => __( 'Bulk Select' ),
3439 'cancelSelection' => __( 'Cancel Selection' ),
3440 'trashSelected' => __( 'Trash Selected' ),
3441 'untrashSelected' => __( 'Untrash Selected' ),
3442 'deleteSelected' => __( 'Delete Selected' ),
3443 'deletePermanently' => __( 'Delete Permanently' ),
3444 'apply' => __( 'Apply' ),
3445 'filterByDate' => __( 'Filter by date' ),
3446 'filterByType' => __( 'Filter by type' ),
3447 'searchMediaLabel' => __( 'Search Media' ),
3448 'searchMediaPlaceholder' => __( 'Search media items...' ), // placeholder (no ellipsis)
3449 'noMedia' => __( 'No media files found.' ),
3452 'attachmentDetails' => __( 'Attachment Details' ),
3455 'insertFromUrlTitle' => __( 'Insert from URL' ),
3458 'setFeaturedImageTitle' => $post_type_object->labels->featured_image,
3459 'setFeaturedImage' => $post_type_object->labels->set_featured_image,
3462 'createGalleryTitle' => __( 'Create Gallery' ),
3463 'editGalleryTitle' => __( 'Edit Gallery' ),
3464 'cancelGalleryTitle' => __( '← Cancel Gallery' ),
3465 'insertGallery' => __( 'Insert gallery' ),
3466 'updateGallery' => __( 'Update gallery' ),
3467 'addToGallery' => __( 'Add to gallery' ),
3468 'addToGalleryTitle' => __( 'Add to Gallery' ),
3469 'reverseOrder' => __( 'Reverse order' ),
3472 'imageDetailsTitle' => __( 'Image Details' ),
3473 'imageReplaceTitle' => __( 'Replace Image' ),
3474 'imageDetailsCancel' => __( 'Cancel Edit' ),
3475 'editImage' => __( 'Edit Image' ),
3478 'chooseImage' => __( 'Choose Image' ),
3479 'selectAndCrop' => __( 'Select and Crop' ),
3480 'skipCropping' => __( 'Skip Cropping' ),
3481 'cropImage' => __( 'Crop Image' ),
3482 'cropYourImage' => __( 'Crop your image' ),
3483 'cropping' => __( 'Cropping…' ),
3484 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
3485 'cropError' => __( 'There has been an error cropping your image.' ),
3488 'audioDetailsTitle' => __( 'Audio Details' ),
3489 'audioReplaceTitle' => __( 'Replace Audio' ),
3490 'audioAddSourceTitle' => __( 'Add Audio Source' ),
3491 'audioDetailsCancel' => __( 'Cancel Edit' ),
3494 'videoDetailsTitle' => __( 'Video Details' ),
3495 'videoReplaceTitle' => __( 'Replace Video' ),
3496 'videoAddSourceTitle' => __( 'Add Video Source' ),
3497 'videoDetailsCancel' => __( 'Cancel Edit' ),
3498 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
3499 'videoAddTrackTitle' => __( 'Add Subtitles' ),
3502 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
3503 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
3504 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
3505 'cancelPlaylistTitle' => __( '← Cancel Audio Playlist' ),
3506 'insertPlaylist' => __( 'Insert audio playlist' ),
3507 'updatePlaylist' => __( 'Update audio playlist' ),
3508 'addToPlaylist' => __( 'Add to audio playlist' ),
3509 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
3512 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
3513 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
3514 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
3515 'cancelVideoPlaylistTitle' => __( '← Cancel Video Playlist' ),
3516 'insertVideoPlaylist' => __( 'Insert video playlist' ),
3517 'updateVideoPlaylist' => __( 'Update video playlist' ),
3518 'addToVideoPlaylist' => __( 'Add to video playlist' ),
3519 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
3523 * Filters the media view settings.
3527 * @param array $settings List of media view settings.
3528 * @param WP_Post $post Post object.
3530 $settings = apply_filters( 'media_view_settings', $settings, $post );
3533 * Filters the media view strings.
3537 * @param array $strings List of media view strings.
3538 * @param WP_Post $post Post object.
3540 $strings = apply_filters( 'media_view_strings', $strings, $post );
3542 $strings['settings'] = $settings;
3544 // Ensure we enqueue media-editor first, that way media-views is
3545 // registered internally before we try to localize it. see #24724.
3546 wp_enqueue_script( 'media-editor' );
3547 wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
3549 wp_enqueue_script( 'media-audiovideo' );
3550 wp_enqueue_style( 'media-views' );
3552 wp_enqueue_script( 'mce-view' );
3553 wp_enqueue_script( 'image-edit' );
3555 wp_enqueue_style( 'imgareaselect' );
3556 wp_plupload_default_settings();
3558 require_once ABSPATH . WPINC . '/media-template.php';
3559 add_action( 'admin_footer', 'wp_print_media_templates' );
3560 add_action( 'wp_footer', 'wp_print_media_templates' );
3561 add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
3564 * Fires at the conclusion of wp_enqueue_media().
3568 do_action( 'wp_enqueue_media' );
3572 * Retrieves media attached to the passed post.
3576 * @param string $type Mime type.
3577 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3578 * @return array Found attachments.
3580 function get_attached_media( $type, $post = 0 ) {
3581 if ( ! $post = get_post( $post ) )
3585 'post_parent' => $post->ID,
3586 'post_type' => 'attachment',
3587 'post_mime_type' => $type,
3588 'posts_per_page' => -1,
3589 'orderby' => 'menu_order',
3594 * Filters arguments used to retrieve media attached to the given post.
3598 * @param array $args Post query arguments.
3599 * @param string $type Mime type of the desired media.
3600 * @param mixed $post Post ID or object.
3602 $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
3604 $children = get_children( $args );
3607 * Filters the list of media attached to the given post.
3611 * @param array $children Associative array of media attached to the given post.
3612 * @param string $type Mime type of the media desired.
3613 * @param mixed $post Post ID or object.
3615 return (array) apply_filters( 'get_attached_media', $children, $type, $post );
3619 * Check the content blob for an audio, video, object, embed, or iframe tags.
3623 * @param string $content A string which might contain media data.
3624 * @param array $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
3625 * @return array A list of found HTML media embeds.
3627 function get_media_embedded_in_content( $content, $types = null ) {
3631 * Filters the embedded media types that are allowed to be returned from the content blob.
3635 * @param array $allowed_media_types An array of allowed media types. Default media types are
3636 * 'audio', 'video', 'object', 'embed', and 'iframe'.
3638 $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
3640 if ( ! empty( $types ) ) {
3641 if ( ! is_array( $types ) ) {
3642 $types = array( $types );
3645 $allowed_media_types = array_intersect( $allowed_media_types, $types );
3648 $tags = implode( '|', $allowed_media_types );
3650 if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
3651 foreach ( $matches[0] as $match ) {
3660 * Retrieves galleries from the passed post's content.
3664 * @param int|WP_Post $post Post ID or object.
3665 * @param bool $html Optional. Whether to return HTML or data in the array. Default true.
3666 * @return array A list of arrays, each containing gallery data and srcs parsed
3667 * from the expanded shortcode.
3669 function get_post_galleries( $post, $html = true ) {
3670 if ( ! $post = get_post( $post ) )
3673 if ( ! has_shortcode( $post->post_content, 'gallery' ) )
3676 $galleries = array();
3677 if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
3678 foreach ( $matches as $shortcode ) {
3679 if ( 'gallery' === $shortcode[2] ) {
3682 $gallery = do_shortcode_tag( $shortcode );
3684 $galleries[] = $gallery;
3686 preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
3687 if ( ! empty( $src ) ) {
3688 foreach ( $src as $s )
3692 $data = shortcode_parse_atts( $shortcode[3] );
3693 $data['src'] = array_values( array_unique( $srcs ) );
3694 $galleries[] = $data;
3701 * Filters the list of all found galleries in the given post.
3705 * @param array $galleries Associative array of all found post galleries.
3706 * @param WP_Post $post Post object.
3708 return apply_filters( 'get_post_galleries', $galleries, $post );
3712 * Check a specified post's content for gallery and, if present, return the first
3716 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3717 * @param bool $html Optional. Whether to return HTML or data. Default is true.
3718 * @return string|array Gallery data and srcs parsed from the expanded shortcode.
3720 function get_post_gallery( $post = 0, $html = true ) {
3721 $galleries = get_post_galleries( $post, $html );
3722 $gallery = reset( $galleries );
3725 * Filters the first-found post gallery.
3729 * @param array $gallery The first-found post gallery.
3730 * @param int|WP_Post $post Post ID or object.
3731 * @param array $galleries Associative array of all found post galleries.
3733 return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
3737 * Retrieve the image srcs from galleries from a post's content, if present
3741 * @see get_post_galleries()
3743 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3744 * @return array A list of lists, each containing image srcs parsed.
3745 * from an expanded shortcode
3747 function get_post_galleries_images( $post = 0 ) {
3748 $galleries = get_post_galleries( $post, false );
3749 return wp_list_pluck( $galleries, 'src' );
3753 * Checks a post's content for galleries and return the image srcs for the first found gallery
3757 * @see get_post_gallery()
3759 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3760 * @return array A list of a gallery's image srcs in order.
3762 function get_post_gallery_images( $post = 0 ) {
3763 $gallery = get_post_gallery( $post, false );
3764 return empty( $gallery['src'] ) ? array() : $gallery['src'];
3768 * Maybe attempts to generate attachment metadata, if missing.
3772 * @param WP_Post $attachment Attachment object.
3774 function wp_maybe_generate_attachment_metadata( $attachment ) {
3775 if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
3779 $file = get_attached_file( $attachment_id );
3780 $meta = wp_get_attachment_metadata( $attachment_id );
3781 if ( empty( $meta ) && file_exists( $file ) ) {
3782 $_meta = get_post_meta( $attachment_id );
3783 $regeneration_lock = 'wp_generating_att_' . $attachment_id;
3784 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
3785 set_transient( $regeneration_lock, $file );
3786 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
3787 delete_transient( $regeneration_lock );
3793 * Tries to convert an attachment URL into a post ID.
3797 * @global wpdb $wpdb WordPress database abstraction object.
3799 * @param string $url The URL to resolve.
3800 * @return int The found post ID, or 0 on failure.
3802 function attachment_url_to_postid( $url ) {
3805 $dir = wp_get_upload_dir();
3808 $site_url = parse_url( $dir['url'] );
3809 $image_path = parse_url( $path );
3811 //force the protocols to match if needed
3812 if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
3813 $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
3816 if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
3817 $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
3820 $sql = $wpdb->prepare(
3821 "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
3824 $post_id = $wpdb->get_var( $sql );
3827 * Filters an attachment id found by URL.
3831 * @param int|null $post_id The post_id (if any) found by the function.
3832 * @param string $url The URL being looked up.
3834 return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
3838 * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
3842 * @return array The relevant CSS file URLs.
3844 function wpview_media_sandbox_styles() {
3845 $version = 'ver=' . get_bloginfo( 'version' );
3846 $mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
3847 $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
3849 return array( $mediaelement, $wpmediaelement );