3 * WordPress API for media display.
10 * Scale down the default size of an image.
12 * This is so that the image is a better fit for the editor and theme.
14 * The `$size` parameter accepts either an array or a string. The supported string
15 * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
16 * 128 width and 96 height in pixels. Also supported for the string value is
17 * 'medium' and 'full'. The 'full' isn't actually supported, but any value other
18 * than the supported will result in the content_width size or 500 if that is
21 * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
22 * called on the calculated array for width and height, respectively. The second
23 * parameter will be the value that was in the $size parameter. The returned
24 * type for the hook is an array with the width as the first element and the
25 * height as the second element.
29 * @param int $width Width of the image in pixels.
30 * @param int $height Height of the image in pixels.
31 * @param string|array $size Optional. Size or array of sizes of what the result image
32 * should be. Accepts any valid image size name. Default 'medium'.
33 * @param string $context Optional. Could be 'display' (like in a theme) or 'edit'
34 * (like inserting into an editor). Default null.
35 * @return array Width and height of what the result image should resize to.
37 function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
38 global $content_width, $_wp_additional_image_sizes;
41 $context = is_admin() ? 'edit' : 'display';
43 if ( is_array($size) ) {
44 $max_width = $size[0];
45 $max_height = $size[1];
47 elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
48 $max_width = intval(get_option('thumbnail_size_w'));
49 $max_height = intval(get_option('thumbnail_size_h'));
50 // last chance thumbnail size defaults
51 if ( !$max_width && !$max_height ) {
56 elseif ( $size == 'medium' ) {
57 $max_width = intval(get_option('medium_size_w'));
58 $max_height = intval(get_option('medium_size_h'));
59 // if no width is set, default to the theme content width if available
61 elseif ( $size == 'large' ) {
63 * We're inserting a large size image into the editor. If it's a really
64 * big image we'll scale it down to fit reasonably within the editor
65 * itself, and within the theme's content width if it's known. The user
66 * can resize it in the editor if they wish.
68 $max_width = intval(get_option('large_size_w'));
69 $max_height = intval(get_option('large_size_h'));
70 if ( intval($content_width) > 0 )
71 $max_width = min( intval($content_width), $max_width );
72 } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
73 $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
74 $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
75 if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
76 $max_width = min( intval($content_width), $max_width );
78 // $size == 'full' has no constraint
81 $max_height = $height;
85 * Filter the maximum image size dimensions for the editor.
89 * @param array $max_image_size An array with the width as the first element,
90 * and the height as the second element.
91 * @param string|array $size Size of what the result image should be.
92 * @param string $context The context the image is being resized for.
93 * Possible values are 'display' (like in a theme)
94 * or 'edit' (like inserting into an editor).
96 list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
98 return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
102 * Retrieve width and height attributes using given width and height values.
104 * Both attributes are required in the sense that both parameters must have a
105 * value, but are optional in that if you set them to false or null, then they
106 * will not be added to the returned string.
108 * You can set the value using a string, but it will only take numeric values.
109 * If you wish to put 'px' after the numbers, then it will be stripped out of
114 * @param int|string $width Image width in pixels.
115 * @param int|string $height Image height in pixels.
116 * @return string HTML attributes for width and, or height.
118 function image_hwstring( $width, $height ) {
121 $out .= 'width="'.intval($width).'" ';
123 $out .= 'height="'.intval($height).'" ';
128 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
130 * Array with image url, width, height, and whether is intermediate size, in
131 * that order is returned on success is returned. $is_intermediate is true if
132 * $url is a resized image, false if it is the original.
134 * The URL might be the original image, or it might be a resized version. This
135 * function won't create a new resized copy, it will just return an already
136 * resized one if it exists.
138 * A plugin may use the 'image_downsize' filter to hook into and offer image
139 * resizing services for images. The hook must return an array with the same
140 * elements that are returned in the function. The first element being the URL
141 * to the new image that was resized.
145 * @param int $id Attachment ID for image.
146 * @param array|string $size Optional. Image size to scale to. Accepts a registered image size
147 * or flat array of height and width values. Default 'medium'.
148 * @return bool|array False on failure, array on success.
150 function image_downsize( $id, $size = 'medium' ) {
152 if ( !wp_attachment_is_image($id) )
156 * Filter whether to preempt the output of image_downsize().
158 * Passing a truthy value to the filter will effectively short-circuit
159 * down-sizing the image, returning that value as output instead.
163 * @param bool $downsize Whether to short-circuit the image downsize. Default false.
164 * @param int $id Attachment ID for image.
165 * @param array|string $size Size of image, either array or string. Default 'medium'.
167 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
171 $img_url = wp_get_attachment_url($id);
172 $meta = wp_get_attachment_metadata($id);
173 $width = $height = 0;
174 $is_intermediate = false;
175 $img_url_basename = wp_basename($img_url);
177 // try for a new style intermediate size
178 if ( $intermediate = image_get_intermediate_size($id, $size) ) {
179 $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
180 $width = $intermediate['width'];
181 $height = $intermediate['height'];
182 $is_intermediate = true;
184 elseif ( $size == 'thumbnail' ) {
185 // fall back to the old thumbnail
186 if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
187 $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
190 $is_intermediate = true;
193 if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
194 // any other type: use the real image
195 $width = $meta['width'];
196 $height = $meta['height'];
200 // we have the actual image size, but might need to further constrain it if content_width is narrower
201 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
203 return array( $img_url, $width, $height, $is_intermediate );
210 * Register a new image size.
212 * Cropping behavior for the image size is dependent on the value of $crop:
213 * 1. If false (default), images will be scaled, not cropped.
214 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
215 * - x_crop_position accepts 'left' 'center', or 'right'.
216 * - y_crop_position accepts 'top', 'center', or 'bottom'.
217 * Images will be cropped to the specified dimensions within the defined crop area.
218 * 3. If true, images will be cropped to the specified dimensions using center positions.
222 * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
224 * @param string $name Image size identifier.
225 * @param int $width Image width in pixels.
226 * @param int $height Image height in pixels.
227 * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
228 * An array can specify positioning of the crop area. Default false.
230 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
231 global $_wp_additional_image_sizes;
233 $_wp_additional_image_sizes[ $name ] = array(
234 'width' => absint( $width ),
235 'height' => absint( $height ),
241 * Check if an image size exists.
245 * @param string $name The image size to check.
246 * @return bool True if the image size exists, false if not.
248 function has_image_size( $name ) {
249 global $_wp_additional_image_sizes;
251 return isset( $_wp_additional_image_sizes[ $name ] );
255 * Remove a new image size.
259 * @param string $name The image size to remove.
260 * @return bool True if the image size was successfully removed, false on failure.
262 function remove_image_size( $name ) {
263 global $_wp_additional_image_sizes;
265 if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
266 unset( $_wp_additional_image_sizes[ $name ] );
274 * Registers an image size for the post thumbnail.
278 * @see add_image_size() for details on cropping behavior.
280 * @param int $width Image width in pixels.
281 * @param int $height Image height in pixels.
282 * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
283 * An array can specify positioning of the crop area. Default false.
285 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
286 add_image_size( 'post-thumbnail', $width, $height, $crop );
290 * Gets an img tag for an image attachment, scaling it down if requested.
292 * The filter 'get_image_tag_class' allows for changing the class name for the
293 * image without having to use regular expressions on the HTML content. The
294 * parameters are: what WordPress will use for the class, the Attachment ID,
295 * image align value, and the size the image should be.
297 * The second filter 'get_image_tag' has the HTML content, which can then be
298 * further manipulated by a plugin to change all attribute values and even HTML
303 * @param int $id Attachment ID.
304 * @param string $alt Image Description for the alt attribute.
305 * @param string $title Image Description for the title attribute.
306 * @param string $align Part of the class name for aligning the image.
307 * @param string|array $size Optional. Registered image size to retrieve a tag for, or flat array
308 * of height and width values. Default 'medium'.
309 * @return string HTML IMG element for given image attachment
311 function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
313 list( $img_src, $width, $height ) = image_downsize($id, $size);
314 $hwstring = image_hwstring($width, $height);
316 $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
318 $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
321 * Filter the value of the attachment's image tag class attribute.
325 * @param string $class CSS class name or space-separated list of classes.
326 * @param int $id Attachment ID.
327 * @param string $align Part of the class name for aligning the image.
328 * @param string $size Optional. Default is 'medium'.
330 $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
332 $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
335 * Filter the HTML content for the image tag.
339 * @param string $html HTML content for the image.
340 * @param int $id Attachment ID.
341 * @param string $alt Alternate text.
342 * @param string $title Attachment title.
343 * @param string $align Part of the class name for aligning the image.
344 * @param string $size Optional. Default is 'medium'.
346 $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
352 * Calculates the new dimensions for a down-sampled image.
354 * If either width or height are empty, no constraint is applied on
359 * @param int $current_width Current width of the image.
360 * @param int $current_height Current height of the image.
361 * @param int $max_width Optional. Max width in pixels to constrain to. Default 0.
362 * @param int $max_height Optional. Max height in pixels to constrain to. Default 0.
363 * @return array First item is the width, the second item is the height.
365 function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
366 if ( !$max_width && !$max_height )
367 return array( $current_width, $current_height );
369 $width_ratio = $height_ratio = 1.0;
370 $did_width = $did_height = false;
372 if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
373 $width_ratio = $max_width / $current_width;
377 if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
378 $height_ratio = $max_height / $current_height;
382 // Calculate the larger/smaller ratios
383 $smaller_ratio = min( $width_ratio, $height_ratio );
384 $larger_ratio = max( $width_ratio, $height_ratio );
386 if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
387 // The larger ratio is too big. It would result in an overflow.
388 $ratio = $smaller_ratio;
390 // The larger ratio fits, and is likely to be a more "snug" fit.
391 $ratio = $larger_ratio;
394 // Very small dimensions may result in 0, 1 should be the minimum.
395 $w = max ( 1, (int) round( $current_width * $ratio ) );
396 $h = max ( 1, (int) round( $current_height * $ratio ) );
398 // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
399 // 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.
400 // Thus we look for dimensions that are one pixel shy of the max value and bump them up
402 // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
403 if ( $did_width && $w == $max_width - 1 ) {
404 $w = $max_width; // Round it up
407 // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
408 if ( $did_height && $h == $max_height - 1 ) {
409 $h = $max_height; // Round it up
413 * Filter dimensions to constrain down-sampled images to.
417 * @param array $dimensions The image width and height.
418 * @param int $current_width The current width of the image.
419 * @param int $current_height The current height of the image.
420 * @param int $max_width The maximum width permitted.
421 * @param int $max_height The maximum height permitted.
423 return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
427 * Retrieves calculated resize dimensions for use in WP_Image_Editor.
429 * Calculates dimensions and coordinates for a resized image that fits
430 * within a specified width and height.
432 * Cropping behavior is dependent on the value of $crop:
433 * 1. If false (default), images will not be cropped.
434 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
435 * - x_crop_position accepts 'left' 'center', or 'right'.
436 * - y_crop_position accepts 'top', 'center', or 'bottom'.
437 * Images will be cropped to the specified dimensions within the defined crop area.
438 * 3. If true, images will be cropped to the specified dimensions using center positions.
442 * @param int $orig_w Original width in pixels.
443 * @param int $orig_h Original height in pixels.
444 * @param int $dest_w New width in pixels.
445 * @param int $dest_h New height in pixels.
446 * @param bool|array $crop Optional. Whether to crop image to specified height and width or resize.
447 * An array can specify positioning of the crop area. Default false.
448 * @return bool|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
450 function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
452 if ($orig_w <= 0 || $orig_h <= 0)
454 // at least one of dest_w or dest_h must be specific
455 if ($dest_w <= 0 && $dest_h <= 0)
459 * Filter whether to preempt calculating the image resize dimensions.
461 * Passing a non-null value to the filter will effectively short-circuit
462 * image_resize_dimensions(), returning that value instead.
466 * @param null|mixed $null Whether to preempt output of the resize dimensions.
467 * @param int $orig_w Original width in pixels.
468 * @param int $orig_h Original height in pixels.
469 * @param int $dest_w New width in pixels.
470 * @param int $dest_h New height in pixels.
471 * @param bool|array $crop Whether to crop image to specified height and width or resize.
472 * An array can specify positioning of the crop area. Default false.
474 $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
475 if ( null !== $output )
479 // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
480 $aspect_ratio = $orig_w / $orig_h;
481 $new_w = min($dest_w, $orig_w);
482 $new_h = min($dest_h, $orig_h);
485 $new_w = (int) round( $new_h * $aspect_ratio );
489 $new_h = (int) round( $new_w / $aspect_ratio );
492 $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
494 $crop_w = round($new_w / $size_ratio);
495 $crop_h = round($new_h / $size_ratio);
497 if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
498 $crop = array( 'center', 'center' );
501 list( $x, $y ) = $crop;
503 if ( 'left' === $x ) {
505 } elseif ( 'right' === $x ) {
506 $s_x = $orig_w - $crop_w;
508 $s_x = floor( ( $orig_w - $crop_w ) / 2 );
511 if ( 'top' === $y ) {
513 } elseif ( 'bottom' === $y ) {
514 $s_y = $orig_h - $crop_h;
516 $s_y = floor( ( $orig_h - $crop_h ) / 2 );
519 // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
526 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
529 // if the resulting image would be the same size or larger we don't want to resize it
530 if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
534 // the return array matches the parameters to imagecopyresampled()
535 // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
536 return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
541 * Resizes an image to make a thumbnail or intermediate size.
543 * The returned array has the file size, the image width, and image height. The
544 * filter 'image_make_intermediate_size' can be used to hook in and change the
545 * values of the returned array. The only parameter is the resized file path.
549 * @param string $file File path.
550 * @param int $width Image width.
551 * @param int $height Image height.
552 * @param bool $crop Optional. Whether to crop image to specified height and width or resize.
554 * @return bool|array False, if no image was created. Metadata array on success.
556 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
557 if ( $width || $height ) {
558 $editor = wp_get_image_editor( $file );
560 if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
563 $resized_file = $editor->save();
565 if ( ! is_wp_error( $resized_file ) && $resized_file ) {
566 unset( $resized_file['path'] );
567 return $resized_file;
574 * Retrieves the image's intermediate size (resized) path, width, and height.
576 * The $size parameter can be an array with the width and height respectively.
577 * If the size matches the 'sizes' metadata array for width and height, then it
578 * will be used. If there is no direct match, then the nearest image size larger
579 * than the specified size will be used. If nothing is found, then the function
580 * will break out and return false.
582 * The metadata 'sizes' is used for compatible sizes that can be used for the
583 * parameter $size value.
585 * The url path will be given, when the $size parameter is a string.
587 * If you are passing an array for the $size, you should consider using
588 * add_image_size() so that a cropped version is generated. It's much more
589 * efficient than having to find the closest-sized image and then having the
590 * browser scale down the image.
594 * @param int $post_id Attachment ID.
595 * @param array|string $size Optional. Registered image size to retrieve or flat array of height
596 * and width dimensions. Default 'thumbnail'.
597 * @return bool|array False on failure or array of file path, width, and height on success.
599 function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
600 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
603 // get the best one for a specified set of dimensions
604 if ( is_array($size) && !empty($imagedata['sizes']) ) {
607 foreach ( $imagedata['sizes'] as $_size => $data ) {
608 // already cropped to width or height; so use this size
609 if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
610 $file = $data['file'];
611 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
612 return compact( 'file', 'width', 'height' );
614 // add to lookup table: area => size
615 $areas[$data['width'] * $data['height']] = $_size;
617 if ( !$size || !empty($areas) ) {
618 // find for the smallest image not smaller than the desired size
620 foreach ( $areas as $_size ) {
621 $data = $imagedata['sizes'][$_size];
622 if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
623 // Skip images with unexpectedly divergent aspect ratios (crops)
624 // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
625 $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
626 // If the size doesn't match within one pixel, then it is of a different aspect ratio, so we skip it, unless it's the thumbnail size
627 if ( 'thumbnail' != $_size && ( !$maybe_cropped || ( $maybe_cropped[4] != $data['width'] && $maybe_cropped[4] + 1 != $data['width'] ) || ( $maybe_cropped[5] != $data['height'] && $maybe_cropped[5] + 1 != $data['height'] ) ) )
629 // If we're still here, then we're going to use this size
630 $file = $data['file'];
631 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
632 return compact( 'file', 'width', 'height' );
638 if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
641 $data = $imagedata['sizes'][$size];
642 // include the full filesystem path of the intermediate file
643 if ( empty($data['path']) && !empty($data['file']) ) {
644 $file_url = wp_get_attachment_url($post_id);
645 $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
646 $data['url'] = path_join( dirname($file_url), $data['file'] );
652 * Gets the available intermediate image sizes.
656 * @global array $_wp_additional_image_sizes
658 * @return array Returns a filtered array of image size strings.
660 function get_intermediate_image_sizes() {
661 global $_wp_additional_image_sizes;
662 $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
663 if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
664 $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
667 * Filter the list of intermediate image sizes.
671 * @param array $image_sizes An array of intermediate image sizes. Defaults
672 * are 'thumbnail', 'medium', 'large'.
674 return apply_filters( 'intermediate_image_sizes', $image_sizes );
678 * Retrieve an image to represent an attachment.
680 * A mime icon for files, thumbnail or intermediate size for images.
684 * @param int $attachment_id Image attachment ID.
685 * @param string|array $size Optional. Registered image size to retrieve the source for or a flat
686 * array of height and width dimensions. Default 'thumbnail'.
687 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
688 * @return bool|array Returns an array (url, width, height), or false, if no image is available.
690 function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
692 // get a thumbnail or intermediate image if there is one
693 if ( $image = image_downsize($attachment_id, $size) )
698 if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
699 /** This filter is documented in wp-includes/post.php */
700 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
702 $src_file = $icon_dir . '/' . wp_basename($src);
703 @list($width, $height) = getimagesize($src_file);
705 if ( $src && $width && $height )
706 return array( $src, $width, $height );
711 * Get an HTML img element representing an image attachment
713 * While `$size` will accept an array, it is better to register a size with
714 * add_image_size() so that a cropped version is generated. It's much more
715 * efficient than having to find the closest-sized image and then having the
716 * browser scale down the image.
720 * @param int $attachment_id Image attachment ID.
721 * @param string|array $size Optional. Registered image size or flat array of height and width
722 * dimensions. Default 'thumbnail'.
723 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
724 * @param string|array $attr Optional. Attributes for the image markup. Default empty.
725 * @return string HTML img element or empty string on failure.
727 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
730 $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
732 list($src, $width, $height) = $image;
733 $hwstring = image_hwstring($width, $height);
735 if ( is_array( $size_class ) ) {
736 $size_class = join( 'x', $size_class );
738 $attachment = get_post($attachment_id);
739 $default_attr = array(
741 'class' => "attachment-$size_class",
742 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
744 if ( empty($default_attr['alt']) )
745 $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
746 if ( empty($default_attr['alt']) )
747 $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
749 $attr = wp_parse_args($attr, $default_attr);
752 * Filter the list of attachment image attributes.
756 * @param array $attr Attributes for the image markup.
757 * @param WP_Post $attachment Image attachment post.
758 * @param string|array $size Requested size.
760 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
761 $attr = array_map( 'esc_attr', $attr );
762 $html = rtrim("<img $hwstring");
763 foreach ( $attr as $name => $value ) {
764 $html .= " $name=" . '"' . $value . '"';
773 * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
775 * Uses the 'begin_fetch_post_thumbnail_html' and 'end_fetch_post_thumbnail_html' action hooks to
776 * dynamically add/remove itself so as to only filter post thumbnails.
781 * @param array $attr Thumbnail attributes including src, class, alt, title.
782 * @return array Modified array of attributes including the new 'wp-post-image' class.
784 function _wp_post_thumbnail_class_filter( $attr ) {
785 $attr['class'] .= ' wp-post-image';
790 * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
791 * filter hook. Internal use only.
796 * @param array $attr Thumbnail attributes including src, class, alt, title.
798 function _wp_post_thumbnail_class_filter_add( $attr ) {
799 add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
803 * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
804 * filter hook. Internal use only.
809 * @param array $attr Thumbnail attributes including src, class, alt, title.
811 function _wp_post_thumbnail_class_filter_remove( $attr ) {
812 remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
815 add_shortcode('wp_caption', 'img_caption_shortcode');
816 add_shortcode('caption', 'img_caption_shortcode');
819 * Builds the Caption shortcode output.
821 * Allows a plugin to replace the content that would otherwise be returned. The
822 * filter is 'img_caption_shortcode' and passes an empty string, the attr
823 * parameter and the content parameter values.
825 * The supported attributes for the shortcode are 'id', 'align', 'width', and
830 * @param array $attr {
831 * Attributes of the caption shortcode.
833 * @type string $id ID of the div element for the caption.
834 * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
835 * 'aligncenter', alignright', 'alignnone'.
836 * @type int $width The width of the caption, in pixels.
837 * @type string $caption The caption text.
838 * @type string $class Additional class name(s) added to the caption container.
840 * @param string $content Shortcode content.
841 * @return string HTML content to display the caption.
843 function img_caption_shortcode( $attr, $content = null ) {
844 // New-style shortcode with the caption inside the shortcode with the link and image tags.
845 if ( ! isset( $attr['caption'] ) ) {
846 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
847 $content = $matches[1];
848 $attr['caption'] = trim( $matches[2] );
853 * Filter the default caption shortcode output.
855 * If the filtered output isn't empty, it will be used instead of generating
856 * the default caption template.
860 * @see img_caption_shortcode()
862 * @param string $output The caption output. Default empty.
863 * @param array $attr Attributes of the caption shortcode.
864 * @param string $content The image element, possibly wrapped in a hyperlink.
866 $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
870 $atts = shortcode_atts( array(
872 'align' => 'alignnone',
876 ), $attr, 'caption' );
878 $atts['width'] = (int) $atts['width'];
879 if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
882 if ( ! empty( $atts['id'] ) )
883 $atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';
885 $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
887 if ( current_theme_supports( 'html5', 'caption' ) ) {
888 return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
889 . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
892 $caption_width = 10 + $atts['width'];
895 * Filter the width of an image's caption.
897 * By default, the caption is 10 pixels greater than the width of the image,
898 * to prevent post content from running up against a floated image.
902 * @see img_caption_shortcode()
904 * @param int $caption_width Width of the caption in pixels. To remove this inline style,
906 * @param array $atts Attributes of the caption shortcode.
907 * @param string $content The image element, possibly wrapped in a hyperlink.
909 $caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
912 if ( $caption_width )
913 $style = 'style="width: ' . (int) $caption_width . 'px" ';
915 return '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
916 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
919 add_shortcode('gallery', 'gallery_shortcode');
922 * Builds the Gallery shortcode output.
924 * This implements the functionality of the Gallery Shortcode for displaying
925 * WordPress images on a post.
929 * @param array $attr {
930 * Attributes of the gallery shortcode.
932 * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
933 * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
934 * Accepts any valid SQL ORDERBY statement.
935 * @type int $id Post ID.
936 * @type string $itemtag HTML tag to use for each image in the gallery.
937 * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
938 * @type string $icontag HTML tag to use for each image's icon.
939 * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
940 * @type string $captiontag HTML tag to use for each image's caption.
941 * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
942 * @type int $columns Number of columns of images to display. Default 3.
943 * @type string $size Size of the images to display. Default 'thumbnail'.
944 * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
945 * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
946 * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
947 * @type string $link What to link each image to. Default empty (links to the attachment page).
948 * Accepts 'file', 'none'.
950 * @return string HTML content to display gallery.
952 function gallery_shortcode( $attr ) {
955 static $instance = 0;
958 if ( ! empty( $attr['ids'] ) ) {
959 // 'ids' is explicitly ordered, unless you specify otherwise.
960 if ( empty( $attr['orderby'] ) ) {
961 $attr['orderby'] = 'post__in';
963 $attr['include'] = $attr['ids'];
967 * Filter the default gallery shortcode output.
969 * If the filtered output isn't empty, it will be used instead of generating
970 * the default gallery template.
973 * @since 4.2.0 The `$instance` parameter was added.
975 * @see gallery_shortcode()
977 * @param string $output The gallery output. Default empty.
978 * @param array $attr Attributes of the gallery shortcode.
979 * @param int $instance Unique numeric ID of this gallery shortcode instance.
981 $output = apply_filters( 'post_gallery', '', $attr, $instance );
982 if ( $output != '' ) {
986 $html5 = current_theme_supports( 'html5', 'gallery' );
987 $atts = shortcode_atts( array(
989 'orderby' => 'menu_order ID',
990 'id' => $post ? $post->ID : 0,
991 'itemtag' => $html5 ? 'figure' : 'dl',
992 'icontag' => $html5 ? 'div' : 'dt',
993 'captiontag' => $html5 ? 'figcaption' : 'dd',
995 'size' => 'thumbnail',
999 ), $attr, 'gallery' );
1001 $id = intval( $atts['id'] );
1003 if ( ! empty( $atts['include'] ) ) {
1004 $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1006 $attachments = array();
1007 foreach ( $_attachments as $key => $val ) {
1008 $attachments[$val->ID] = $_attachments[$key];
1010 } elseif ( ! empty( $atts['exclude'] ) ) {
1011 $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'] ) );
1013 $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1016 if ( empty( $attachments ) ) {
1022 foreach ( $attachments as $att_id => $attachment ) {
1023 $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
1028 $itemtag = tag_escape( $atts['itemtag'] );
1029 $captiontag = tag_escape( $atts['captiontag'] );
1030 $icontag = tag_escape( $atts['icontag'] );
1031 $valid_tags = wp_kses_allowed_html( 'post' );
1032 if ( ! isset( $valid_tags[ $itemtag ] ) ) {
1035 if ( ! isset( $valid_tags[ $captiontag ] ) ) {
1038 if ( ! isset( $valid_tags[ $icontag ] ) ) {
1042 $columns = intval( $atts['columns'] );
1043 $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
1044 $float = is_rtl() ? 'right' : 'left';
1046 $selector = "gallery-{$instance}";
1048 $gallery_style = '';
1051 * Filter whether to print default gallery styles.
1055 * @param bool $print Whether to print default gallery styles.
1056 * Defaults to false if the theme supports HTML5 galleries.
1057 * Otherwise, defaults to true.
1059 if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1061 <style type='text/css'>
1065 #{$selector} .gallery-item {
1069 width: {$itemwidth}%;
1072 border: 2px solid #cfcfcf;
1074 #{$selector} .gallery-caption {
1077 /* see gallery_shortcode() in wp-includes/media.php */
1081 $size_class = sanitize_html_class( $atts['size'] );
1082 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1085 * Filter the default gallery shortcode CSS styles.
1089 * @param string $gallery_style Default CSS styles and opening HTML div container
1090 * for the gallery shortcode output.
1092 $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1095 foreach ( $attachments as $id => $attachment ) {
1097 $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
1098 if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
1099 $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
1100 } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
1101 $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
1103 $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
1105 $image_meta = wp_get_attachment_metadata( $id );
1108 if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
1109 $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1111 $output .= "<{$itemtag} class='gallery-item'>";
1113 <{$icontag} class='gallery-icon {$orientation}'>
1116 if ( $captiontag && trim($attachment->post_excerpt) ) {
1118 <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
1119 " . wptexturize($attachment->post_excerpt) . "
1122 $output .= "</{$itemtag}>";
1123 if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1124 $output .= '<br style="clear: both" />';
1128 if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1130 <br style='clear: both' />";
1140 * Outputs the templates used by playlists.
1144 function wp_underscore_playlist_templates() {
1146 <script type="text/html" id="tmpl-wp-playlist-current-item">
1147 <# if ( data.image ) { #>
1148 <img src="{{ data.thumb.src }}"/>
1150 <div class="wp-playlist-caption">
1151 <span class="wp-playlist-item-meta wp-playlist-item-title">“{{ data.title }}”</span>
1152 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1153 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1156 <script type="text/html" id="tmpl-wp-playlist-item">
1157 <div class="wp-playlist-item">
1158 <a class="wp-playlist-caption" href="{{ data.src }}">
1159 {{ data.index ? ( data.index + '. ' ) : '' }}
1160 <# if ( data.caption ) { #>
1163 <span class="wp-playlist-item-title">“{{{ data.title }}}”</span>
1164 <# if ( data.artists && data.meta.artist ) { #>
1165 <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span>
1169 <# if ( data.meta.length_formatted ) { #>
1170 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1178 * Outputs and enqueue default scripts and styles for playlists.
1182 * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1184 function wp_playlist_scripts( $type ) {
1185 wp_enqueue_style( 'wp-mediaelement' );
1186 wp_enqueue_script( 'wp-playlist' );
1188 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1190 add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1191 add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1195 * Builds the Playlist shortcode output.
1197 * This implements the functionality of the playlist shortcode for displaying
1198 * a collection of WordPress audio or video files in a post.
1202 * @param array $attr {
1203 * Array of default playlist attributes.
1205 * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
1206 * @type string $order Designates ascending or descending order of items in the playlist.
1207 * Accepts 'ASC', 'DESC'. Default 'ASC'.
1208 * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
1209 * passed, this defaults to the order of the $ids array ('post__in').
1210 * Otherwise default is 'menu_order ID'.
1211 * @type int $id If an explicit $ids array is not present, this parameter
1212 * will determine which attachments are used for the playlist.
1213 * Default is the current post ID.
1214 * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
1215 * a playlist will be created from all $type attachments of $id.
1217 * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
1218 * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
1219 * @type bool $tracklist Whether to show or hide the playlist. Default true.
1220 * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
1221 * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
1222 * thumbnail). Default true.
1223 * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
1226 * @return string Playlist output. Empty string if the passed type is unsupported.
1228 function wp_playlist_shortcode( $attr ) {
1229 global $content_width;
1232 static $instance = 0;
1235 if ( ! empty( $attr['ids'] ) ) {
1236 // 'ids' is explicitly ordered, unless you specify otherwise.
1237 if ( empty( $attr['orderby'] ) ) {
1238 $attr['orderby'] = 'post__in';
1240 $attr['include'] = $attr['ids'];
1244 * Filter the playlist output.
1246 * Passing a non-empty value to the filter will short-circuit generation
1247 * of the default playlist output, returning the passed value instead.
1250 * @since 4.2.0 The `$instance` parameter was added.
1252 * @param string $output Playlist output. Default empty.
1253 * @param array $attr An array of shortcode attributes.
1254 * @param int $instance Unique numeric ID of this playlist shortcode instance.
1256 $output = apply_filters( 'post_playlist', '', $attr, $instance );
1257 if ( $output != '' ) {
1261 $atts = shortcode_atts( array(
1264 'orderby' => 'menu_order ID',
1265 'id' => $post ? $post->ID : 0,
1269 'tracklist' => true,
1270 'tracknumbers' => true,
1273 ), $attr, 'playlist' );
1275 $id = intval( $atts['id'] );
1277 if ( $atts['type'] !== 'audio' ) {
1278 $atts['type'] = 'video';
1282 'post_status' => 'inherit',
1283 'post_type' => 'attachment',
1284 'post_mime_type' => $atts['type'],
1285 'order' => $atts['order'],
1286 'orderby' => $atts['orderby']
1289 if ( ! empty( $atts['include'] ) ) {
1290 $args['include'] = $atts['include'];
1291 $_attachments = get_posts( $args );
1293 $attachments = array();
1294 foreach ( $_attachments as $key => $val ) {
1295 $attachments[$val->ID] = $_attachments[$key];
1297 } elseif ( ! empty( $atts['exclude'] ) ) {
1298 $args['post_parent'] = $id;
1299 $args['exclude'] = $atts['exclude'];
1300 $attachments = get_children( $args );
1302 $args['post_parent'] = $id;
1303 $attachments = get_children( $args );
1306 if ( empty( $attachments ) ) {
1312 foreach ( $attachments as $att_id => $attachment ) {
1313 $output .= wp_get_attachment_link( $att_id ) . "\n";
1318 $outer = 22; // default padding and border of wrapper
1320 $default_width = 640;
1321 $default_height = 360;
1323 $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
1324 $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
1327 'type' => $atts['type'],
1328 // don't pass strings to JSON, will be truthy in JS
1329 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
1330 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
1331 'images' => wp_validate_boolean( $atts['images'] ),
1332 'artists' => wp_validate_boolean( $atts['artists'] ),
1336 foreach ( $attachments as $attachment ) {
1337 $url = wp_get_attachment_url( $attachment->ID );
1338 $ftype = wp_check_filetype( $url, wp_get_mime_types() );
1341 'type' => $ftype['type'],
1342 'title' => $attachment->post_title,
1343 'caption' => $attachment->post_excerpt,
1344 'description' => $attachment->post_content
1347 $track['meta'] = array();
1348 $meta = wp_get_attachment_metadata( $attachment->ID );
1349 if ( ! empty( $meta ) ) {
1351 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
1352 if ( ! empty( $meta[ $key ] ) ) {
1353 $track['meta'][ $key ] = $meta[ $key ];
1357 if ( 'video' === $atts['type'] ) {
1358 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1359 $width = $meta['width'];
1360 $height = $meta['height'];
1361 $theme_height = round( ( $height * $theme_width ) / $width );
1363 $width = $default_width;
1364 $height = $default_height;
1367 $track['dimensions'] = array(
1368 'original' => compact( 'width', 'height' ),
1370 'width' => $theme_width,
1371 'height' => $theme_height
1377 if ( $atts['images'] ) {
1378 $thumb_id = get_post_thumbnail_id( $attachment->ID );
1379 if ( ! empty( $thumb_id ) ) {
1380 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
1381 $track['image'] = compact( 'src', 'width', 'height' );
1382 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
1383 $track['thumb'] = compact( 'src', 'width', 'height' );
1385 $src = wp_mime_type_icon( $attachment->ID );
1388 $track['image'] = compact( 'src', 'width', 'height' );
1389 $track['thumb'] = compact( 'src', 'width', 'height' );
1395 $data['tracks'] = $tracks;
1397 $safe_type = esc_attr( $atts['type'] );
1398 $safe_style = esc_attr( $atts['style'] );
1402 if ( 1 === $instance ) {
1404 * Print and enqueue playlist scripts, styles, and JavaScript templates.
1408 * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
1409 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
1411 do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
1413 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
1414 <?php if ( 'audio' === $atts['type'] ): ?>
1415 <div class="wp-playlist-current-item"></div>
1417 <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
1418 echo (int) $theme_width;
1419 ?>"<?php if ( 'video' === $safe_type ):
1420 echo ' height="', (int) $theme_height, '"';
1422 echo ' style="visibility: hidden"';
1423 endif; ?>></<?php echo $safe_type ?>>
1424 <div class="wp-playlist-next"></div>
1425 <div class="wp-playlist-prev"></div>
1428 foreach ( $attachments as $att_id => $attachment ) {
1429 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
1433 <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
1436 return ob_get_clean();
1438 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
1441 * Provides a No-JS Flash fallback as a last resort for audio / video.
1445 * @param string $url The media element URL.
1446 * @return string Fallback HTML.
1448 function wp_mediaelement_fallback( $url ) {
1450 * Filter the Mediaelement fallback output for no-JS.
1454 * @param string $output Fallback output for no-JS.
1455 * @param string $url Media file URL.
1457 return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
1461 * Returns a filtered list of WP-supported audio formats.
1465 * @return array Supported audio formats.
1467 function wp_get_audio_extensions() {
1469 * Filter the list of supported audio formats.
1473 * @param array $extensions An array of support audio formats. Defaults are
1474 * 'mp3', 'ogg', 'wma', 'm4a', 'wav'.
1476 return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
1480 * Returns useful keys to use to lookup data from an attachment's stored metadata.
1484 * @param WP_Post $attachment The current attachment, provided for context.
1485 * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'.
1486 * @return array Key/value pairs of field keys to labels.
1488 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
1490 'artist' => __( 'Artist' ),
1491 'album' => __( 'Album' ),
1494 if ( 'display' === $context ) {
1495 $fields['genre'] = __( 'Genre' );
1496 $fields['year'] = __( 'Year' );
1497 $fields['length_formatted'] = _x( 'Length', 'video or audio' );
1498 } elseif ( 'js' === $context ) {
1499 $fields['bitrate'] = __( 'Bitrate' );
1500 $fields['bitrate_mode'] = __( 'Bitrate Mode' );
1504 * Filter the editable list of keys to look up data from an attachment's metadata.
1508 * @param array $fields Key/value pairs of field keys to labels.
1509 * @param WP_Post $attachment Attachment object.
1510 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
1512 return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
1515 * Builds the Audio shortcode output.
1517 * This implements the functionality of the Audio Shortcode for displaying
1518 * WordPress mp3s in a post.
1522 * @param array $attr {
1523 * Attributes of the audio shortcode.
1525 * @type string $src URL to the source of the audio file. Default empty.
1526 * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
1527 * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
1528 * @type string $preload The 'preload' attribute for the `<audio>` element. Default empty.
1529 * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
1530 * @type string $id The 'id' attribute for the `<audio>` element. Default 'audio-{$post_id}-{$instance}'.
1531 * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
1533 * @param string $content Shortcode content.
1534 * @return string HTML content to display audio.
1536 function wp_audio_shortcode( $attr, $content = '' ) {
1537 $post_id = get_post() ? get_the_ID() : 0;
1539 static $instance = 0;
1543 * Filter the default audio shortcode output.
1545 * If the filtered output isn't empty, it will be used instead of generating the default audio template.
1549 * @param string $html Empty variable to be replaced with shortcode markup.
1550 * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
1551 * @param string $content Shortcode content.
1552 * @param int $instance Unique numeric ID of this audio shortcode instance.
1554 $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
1555 if ( '' !== $override ) {
1561 $default_types = wp_get_audio_extensions();
1562 $defaults_atts = array(
1568 foreach ( $default_types as $type ) {
1569 $defaults_atts[$type] = '';
1572 $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
1575 if ( ! empty( $atts['src'] ) ) {
1576 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
1577 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1578 return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
1581 array_unshift( $default_types, 'src' );
1583 foreach ( $default_types as $ext ) {
1584 if ( ! empty( $atts[ $ext ] ) ) {
1585 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
1586 if ( strtolower( $type['ext'] ) === $ext ) {
1594 $audios = get_attached_media( 'audio', $post_id );
1595 if ( empty( $audios ) ) {
1599 $audio = reset( $audios );
1600 $atts['src'] = wp_get_attachment_url( $audio->ID );
1601 if ( empty( $atts['src'] ) ) {
1605 array_unshift( $default_types, 'src' );
1609 * Filter the media library used for the audio shortcode.
1613 * @param string $library Media library used for the audio shortcode.
1615 $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
1616 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1617 wp_enqueue_style( 'wp-mediaelement' );
1618 wp_enqueue_script( 'wp-mediaelement' );
1622 * Filter the class attribute for the audio shortcode output container.
1626 * @param string $class CSS class or list of space-separated classes.
1629 'class' => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
1630 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
1631 'loop' => wp_validate_boolean( $atts['loop'] ),
1632 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
1633 'preload' => $atts['preload'],
1634 'style' => 'width: 100%; visibility: hidden;',
1637 // These ones should just be omitted altogether if they are blank
1638 foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
1639 if ( empty( $html_atts[$a] ) ) {
1640 unset( $html_atts[$a] );
1644 $attr_strings = array();
1645 foreach ( $html_atts as $k => $v ) {
1646 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1650 if ( 'mediaelement' === $library && 1 === $instance ) {
1651 $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
1653 $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
1656 $source = '<source type="%s" src="%s" />';
1657 foreach ( $default_types as $fallback ) {
1658 if ( ! empty( $atts[ $fallback ] ) ) {
1659 if ( empty( $fileurl ) ) {
1660 $fileurl = $atts[ $fallback ];
1662 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
1663 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
1664 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1668 if ( 'mediaelement' === $library ) {
1669 $html .= wp_mediaelement_fallback( $fileurl );
1671 $html .= '</audio>';
1674 * Filter the audio shortcode output.
1678 * @param string $html Audio shortcode HTML output.
1679 * @param array $atts Array of audio shortcode attributes.
1680 * @param string $audio Audio file.
1681 * @param int $post_id Post ID.
1682 * @param string $library Media library used for the audio shortcode.
1684 return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
1686 add_shortcode( 'audio', 'wp_audio_shortcode' );
1689 * Returns a filtered list of WP-supported video formats.
1693 * @return array List of supported video formats.
1695 function wp_get_video_extensions() {
1697 * Filter the list of supported video formats.
1701 * @param array $extensions An array of support video formats. Defaults are
1702 * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
1704 return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
1708 * Builds the Video shortcode output.
1710 * This implements the functionality of the Video Shortcode for displaying
1711 * WordPress mp4s in a post.
1715 * @param array $attr {
1716 * Attributes of the shortcode.
1718 * @type string $src URL to the source of the video file. Default empty.
1719 * @type int $height Height of the video embed in pixels. Default 360.
1720 * @type int $width Width of the video embed in pixels. Default $content_width or 640.
1721 * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
1722 * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
1723 * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
1724 * @type string $preload The 'preload' attribute for the `<video>` element.
1725 * Default 'metadata'.
1726 * @type string $class The 'class' attribute for the `<video>` element.
1727 * Default 'wp-video-shortcode'.
1728 * @type string $id The 'id' attribute for the `<video>` element.
1729 * Default 'video-{$post_id}-{$instance}'.
1731 * @param string $content Shortcode content.
1732 * @return string HTML content to display video.
1734 function wp_video_shortcode( $attr, $content = '' ) {
1735 global $content_width;
1736 $post_id = get_post() ? get_the_ID() : 0;
1738 static $instance = 0;
1742 * Filter the default video shortcode output.
1744 * If the filtered output isn't empty, it will be used instead of generating
1745 * the default video template.
1749 * @see wp_video_shortcode()
1751 * @param string $html Empty variable to be replaced with shortcode markup.
1752 * @param array $attr Attributes of the video shortcode.
1753 * @param string $content Video shortcode content.
1754 * @param int $instance Unique numeric ID of this video shortcode instance.
1756 $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
1757 if ( '' !== $override ) {
1763 $default_types = wp_get_video_extensions();
1764 $defaults_atts = array(
1769 'preload' => 'metadata',
1774 foreach ( $default_types as $type ) {
1775 $defaults_atts[$type] = '';
1778 $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
1781 // shrink the video so it isn't huge in the admin
1782 if ( $atts['width'] > $defaults_atts['width'] ) {
1783 $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
1784 $atts['width'] = $defaults_atts['width'];
1787 // if the video is bigger than the theme
1788 if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
1789 $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
1790 $atts['width'] = $content_width;
1794 $is_vimeo = $is_youtube = false;
1795 $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
1796 $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
1799 if ( ! empty( $atts['src'] ) ) {
1800 $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
1801 $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
1802 if ( ! $is_youtube && ! $is_vimeo ) {
1803 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
1804 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1805 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
1810 wp_enqueue_script( 'froogaloop' );
1814 array_unshift( $default_types, 'src' );
1816 foreach ( $default_types as $ext ) {
1817 if ( ! empty( $atts[ $ext ] ) ) {
1818 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
1819 if ( strtolower( $type['ext'] ) === $ext ) {
1827 $videos = get_attached_media( 'video', $post_id );
1828 if ( empty( $videos ) ) {
1832 $video = reset( $videos );
1833 $atts['src'] = wp_get_attachment_url( $video->ID );
1834 if ( empty( $atts['src'] ) ) {
1838 array_unshift( $default_types, 'src' );
1842 * Filter the media library used for the video shortcode.
1846 * @param string $library Media library used for the video shortcode.
1848 $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
1849 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1850 wp_enqueue_style( 'wp-mediaelement' );
1851 wp_enqueue_script( 'wp-mediaelement' );
1855 * Filter the class attribute for the video shortcode output container.
1859 * @param string $class CSS class or list of space-separated classes.
1862 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
1863 'id' => sprintf( 'video-%d-%d', $post_id, $instance ),
1864 'width' => absint( $atts['width'] ),
1865 'height' => absint( $atts['height'] ),
1866 'poster' => esc_url( $atts['poster'] ),
1867 'loop' => wp_validate_boolean( $atts['loop'] ),
1868 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
1869 'preload' => $atts['preload'],
1872 // These ones should just be omitted altogether if they are blank
1873 foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
1874 if ( empty( $html_atts[$a] ) ) {
1875 unset( $html_atts[$a] );
1879 $attr_strings = array();
1880 foreach ( $html_atts as $k => $v ) {
1881 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1885 if ( 'mediaelement' === $library && 1 === $instance ) {
1886 $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
1888 $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
1891 $source = '<source type="%s" src="%s" />';
1892 foreach ( $default_types as $fallback ) {
1893 if ( ! empty( $atts[ $fallback ] ) ) {
1894 if ( empty( $fileurl ) ) {
1895 $fileurl = $atts[ $fallback ];
1897 if ( 'src' === $fallback && $is_youtube ) {
1898 $type = array( 'type' => 'video/youtube' );
1899 } elseif ( 'src' === $fallback && $is_vimeo ) {
1900 $type = array( 'type' => 'video/vimeo' );
1902 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
1904 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
1905 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1909 if ( ! empty( $content ) ) {
1910 if ( false !== strpos( $content, "\n" ) ) {
1911 $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
1913 $html .= trim( $content );
1916 if ( 'mediaelement' === $library ) {
1917 $html .= wp_mediaelement_fallback( $fileurl );
1919 $html .= '</video>';
1922 if ( ! empty( $atts['width'] ) ) {
1923 $width_rule = sprintf( 'width: %dpx; ', $atts['width'] );
1925 $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
1928 * Filter the output of the video shortcode.
1932 * @param string $output Video shortcode HTML output.
1933 * @param array $atts Array of video shortcode attributes.
1934 * @param string $video Video file.
1935 * @param int $post_id Post ID.
1936 * @param string $library Media library used for the video shortcode.
1938 return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
1940 add_shortcode( 'video', 'wp_video_shortcode' );
1943 * Displays previous image link that has the same post parent.
1947 * @see adjacent_image_link()
1949 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
1950 * 0 or 'none' will default to 'post_title' or `$text`. Default 'thumbnail'.
1951 * @param string $text Optional. Link text. Default false.
1952 * @return string HTML output for the previous image link.
1954 function previous_image_link( $size = 'thumbnail', $text = false ) {
1955 adjacent_image_link(true, $size, $text);
1959 * Displays next image link that has the same post parent.
1963 * @see adjacent_image_link()
1965 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
1966 * 0 or 'none' will default to 'post_title' or `$text`. Default 'thumbnail'.
1967 * @param string $text Optional. Link text. Default false.
1968 * @return string HTML output for the next image link.
1970 function next_image_link($size = 'thumbnail', $text = false) {
1971 adjacent_image_link(false, $size, $text);
1975 * Displays next or previous image link that has the same post parent.
1977 * Retrieves the current attachment object from the $post global.
1981 * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
1982 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
1983 * Default 'thumbnail'.
1984 * @param bool $text Optional. Link text. Default false.
1985 * @return string The adjacent image link.
1987 function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
1989 $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' ) ) );
1991 foreach ( $attachments as $k => $attachment ) {
1992 if ( $attachment->ID == $post->ID ) {
2000 if ( $attachments ) {
2001 $k = $prev ? $k - 1 : $k + 1;
2003 if ( isset( $attachments[ $k ] ) ) {
2004 $attachment_id = $attachments[ $k ]->ID;
2005 $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
2009 $adjacent = $prev ? 'previous' : 'next';
2012 * Filter the adjacent image link.
2014 * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
2015 * either 'next', or 'previous'.
2019 * @param string $output Adjacent image HTML markup.
2020 * @param int $attachment_id Attachment ID
2021 * @param string $size Image size.
2022 * @param string $text Link text.
2024 echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
2028 * Retrieves taxonomies attached to given the attachment.
2032 * @param int|array|object $attachment Attachment ID, data array, or data object.
2033 * @return array Empty array on failure. List of taxonomies on success.
2035 function get_attachment_taxonomies( $attachment ) {
2036 if ( is_int( $attachment ) ) {
2037 $attachment = get_post( $attachment );
2038 } elseif ( is_array( $attachment ) ) {
2039 $attachment = (object) $attachment;
2041 if ( ! is_object($attachment) )
2044 $filename = basename($attachment->guid);
2046 $objects = array('attachment');
2048 if ( false !== strpos($filename, '.') )
2049 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
2050 if ( !empty($attachment->post_mime_type) ) {
2051 $objects[] = 'attachment:' . $attachment->post_mime_type;
2052 if ( false !== strpos($attachment->post_mime_type, '/') )
2053 foreach ( explode('/', $attachment->post_mime_type) as $token )
2054 if ( !empty($token) )
2055 $objects[] = "attachment:$token";
2058 $taxonomies = array();
2059 foreach ( $objects as $object )
2060 if ( $taxes = get_object_taxonomies($object) )
2061 $taxonomies = array_merge($taxonomies, $taxes);
2063 return array_unique($taxonomies);
2067 * Retrieves all of the taxonomy names that are registered for attachments.
2069 * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
2073 * @see get_taxonomies()
2075 * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
2077 * @return array The names of all taxonomy of $object_type.
2079 function get_taxonomies_for_attachments( $output = 'names' ) {
2080 $taxonomies = array();
2081 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
2082 foreach ( $taxonomy->object_type as $object_type ) {
2083 if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
2084 if ( 'names' == $output )
2085 $taxonomies[] = $taxonomy->name;
2087 $taxonomies[ $taxonomy->name ] = $taxonomy;
2097 * Create new GD image resource with transparency support
2099 * @todo: Deprecate if possible.
2103 * @param int $width Image width in pixels.
2104 * @param int $height Image height in pixels..
2105 * @return resource The GD image resource.
2107 function wp_imagecreatetruecolor($width, $height) {
2108 $img = imagecreatetruecolor($width, $height);
2109 if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
2110 imagealphablending($img, false);
2111 imagesavealpha($img, true);
2117 * Registers an embed handler.
2119 * Should probably only be used for sites that do not support oEmbed.
2123 * @see WP_Embed::register_handler()
2125 * @param string $id An internal ID/name for the handler. Needs to be unique.
2126 * @param string $regex The regex that will be used to see if this handler should be used for a URL.
2127 * @param callback $callback The callback function that will be called if the regex is matched.
2128 * @param int $priority Optional. Used to specify the order in which the registered handlers will
2129 * be tested. Default 10.
2131 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
2133 $wp_embed->register_handler( $id, $regex, $callback, $priority );
2137 * Unregisters a previously-registered embed handler.
2141 * @see WP_Embed::unregister_handler()
2143 * @param string $id The handler ID that should be removed.
2144 * @param int $priority Optional. The priority of the handler to be removed. Default 10.
2146 function wp_embed_unregister_handler( $id, $priority = 10 ) {
2148 $wp_embed->unregister_handler( $id, $priority );
2152 * Create default array of embed parameters.
2154 * The width defaults to the content width as specified by the theme. If the
2155 * theme does not specify a content width, then 500px is used.
2157 * The default height is 1.5 times the width, or 1000px, whichever is smaller.
2159 * The 'embed_defaults' filter can be used to adjust either of these values.
2163 * @param string $url Optional. The URL that should be embedded. Default empty.
2165 * @return array Default embed parameters.
2167 function wp_embed_defaults( $url = '' ) {
2168 if ( ! empty( $GLOBALS['content_width'] ) )
2169 $width = (int) $GLOBALS['content_width'];
2171 if ( empty( $width ) )
2174 $height = min( ceil( $width * 1.5 ), 1000 );
2177 * Filter the default array of embed dimensions.
2181 * @param int $width Width of the embed in pixels.
2182 * @param int $height Height of the embed in pixels.
2183 * @param string $url The URL that should be embedded.
2185 return apply_filters( 'embed_defaults', compact( 'width', 'height' ), $url );
2189 * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
2193 * @see wp_constrain_dimensions()
2195 * @param int $example_width The width of an example embed.
2196 * @param int $example_height The height of an example embed.
2197 * @param int $max_width The maximum allowed width.
2198 * @param int $max_height The maximum allowed height.
2199 * @return array The maximum possible width and height based on the example ratio.
2201 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
2202 $example_width = (int) $example_width;
2203 $example_height = (int) $example_height;
2204 $max_width = (int) $max_width;
2205 $max_height = (int) $max_height;
2207 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
2211 * Attempts to fetch the embed HTML for a provided URL using oEmbed.
2217 * @param string $url The URL that should be embedded.
2218 * @param array $args Optional. Additional arguments and parameters for retrieving embed HTML.
2220 * @return false|string False on failure or the embed HTML on success.
2222 function wp_oembed_get( $url, $args = '' ) {
2223 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2224 $oembed = _wp_oembed_get_object();
2225 return $oembed->get_html( $url, $args );
2229 * Adds a URL format and oEmbed provider URL pair.
2235 * @param string $format The format of URL that this provider can handle. You can use asterisks
2237 * @param string $provider The URL to the oEmbed provider.
2238 * @param boolean $regex Optional. Whether the `$format` parameter is in a RegEx format. Default false.
2240 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
2241 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2243 if ( did_action( 'plugins_loaded' ) ) {
2244 $oembed = _wp_oembed_get_object();
2245 $oembed->providers[$format] = array( $provider, $regex );
2247 WP_oEmbed::_add_provider_early( $format, $provider, $regex );
2252 * Removes an oEmbed provider.
2258 * @param string $format The URL format for the oEmbed provider to remove.
2259 * @return bool Was the provider removed successfully?
2261 function wp_oembed_remove_provider( $format ) {
2262 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2264 if ( did_action( 'plugins_loaded' ) ) {
2265 $oembed = _wp_oembed_get_object();
2267 if ( isset( $oembed->providers[ $format ] ) ) {
2268 unset( $oembed->providers[ $format ] );
2272 WP_oEmbed::_remove_provider_early( $format );
2279 * Determines if default embed handlers should be loaded.
2281 * Checks to make sure that the embeds library hasn't already been loaded. If
2282 * it hasn't, then it will load the embeds library.
2286 * @see wp_embed_register_handler()
2288 function wp_maybe_load_embeds() {
2290 * Filter whether to load the default embed handlers.
2292 * Returning a falsey value will prevent loading the default embed handlers.
2296 * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
2298 if ( ! apply_filters( 'load_default_embeds', true ) ) {
2302 wp_embed_register_handler( 'youtube_embed_url', '#https?://(www.)?youtube\.com/embed/([^/]+)#i', 'wp_embed_handler_youtube' );
2304 wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
2307 * Filter the audio embed handler callback.
2311 * @param callback $handler Audio embed handler callback function.
2313 wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
2316 * Filter the video embed handler callback.
2320 * @param callback $handler Video embed handler callback function.
2322 wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
2326 * The Google Video embed handler callback.
2328 * Google Video does not support oEmbed.
2330 * @see WP_Embed::register_handler()
2331 * @see WP_Embed::shortcode()
2333 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2334 * @param array $attr Embed attributes.
2335 * @param string $url The original URL that was matched by the regex.
2336 * @param array $rawattr The original unmodified attributes.
2337 * @return string The embed HTML.
2339 function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
2340 // If the user supplied a fixed width AND height, use it
2341 if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
2342 $width = (int) $rawattr['width'];
2343 $height = (int) $rawattr['height'];
2345 list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
2349 * Filter the Google Video embed output.
2353 * @param string $html Google Video HTML embed markup.
2354 * @param array $matches The RegEx matches from the provided regex.
2355 * @param array $attr An array of embed attributes.
2356 * @param string $url The original URL that was matched by the regex.
2357 * @param array $rawattr The original unmodified attributes.
2359 return apply_filters( 'embed_googlevideo', '<embed type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docid=' . esc_attr($matches[2]) . '&hl=en&fs=true" style="width:' . esc_attr($width) . 'px;height:' . esc_attr($height) . 'px" allowFullScreen="true" allowScriptAccess="always" />', $matches, $attr, $url, $rawattr );
2363 * YouTube iframe embed handler callback.
2365 * Catches YouTube iframe embed URLs that are not parsable by oEmbed but can be translated into a URL that is.
2369 * @param array $matches The RegEx matches from the provided regex when calling
2370 * wp_embed_register_handler().
2371 * @param array $attr Embed attributes.
2372 * @param string $url The original URL that was matched by the regex.
2373 * @param array $rawattr The original unmodified attributes.
2374 * @return string The embed HTML.
2376 function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
2378 $embed = $wp_embed->autoembed( "https://youtube.com/watch?v={$matches[2]}" );
2381 * Filter the YoutTube embed output.
2385 * @see wp_embed_handler_youtube()
2387 * @param string $embed YouTube embed output.
2388 * @param array $attr An array of embed attributes.
2389 * @param string $url The original URL that was matched by the regex.
2390 * @param array $rawattr The original unmodified attributes.
2392 return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
2396 * Audio embed handler callback.
2400 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2401 * @param array $attr Embed attributes.
2402 * @param string $url The original URL that was matched by the regex.
2403 * @param array $rawattr The original unmodified attributes.
2404 * @return string The embed HTML.
2406 function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
2407 $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
2410 * Filter the audio embed output.
2414 * @param string $audio Audio embed output.
2415 * @param array $attr An array of embed attributes.
2416 * @param string $url The original URL that was matched by the regex.
2417 * @param array $rawattr The original unmodified attributes.
2419 return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
2423 * Video embed handler callback.
2427 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2428 * @param array $attr Embed attributes.
2429 * @param string $url The original URL that was matched by the regex.
2430 * @param array $rawattr The original unmodified attributes.
2431 * @return string The embed HTML.
2433 function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
2435 if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
2436 $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
2437 $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
2439 $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
2442 * Filter the video embed output.
2446 * @param string $video Video embed output.
2447 * @param array $attr An array of embed attributes.
2448 * @param string $url The original URL that was matched by the regex.
2449 * @param array $rawattr The original unmodified attributes.
2451 return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
2455 * Converts a shorthand byte value to an integer byte value.
2459 * @param string $size A shorthand byte value.
2460 * @return int An integer byte value.
2462 function wp_convert_hr_to_bytes( $size ) {
2463 $size = strtolower( $size );
2464 $bytes = (int) $size;
2465 if ( strpos( $size, 'k' ) !== false )
2466 $bytes = intval( $size ) * 1024;
2467 elseif ( strpos( $size, 'm' ) !== false )
2468 $bytes = intval($size) * 1024 * 1024;
2469 elseif ( strpos( $size, 'g' ) !== false )
2470 $bytes = intval( $size ) * 1024 * 1024 * 1024;
2475 * Determines the maximum upload size allowed in php.ini.
2479 * @return int Allowed upload size.
2481 function wp_max_upload_size() {
2482 $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2483 $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2486 * Filter the maximum upload size allowed in php.ini.
2490 * @param int $size Max upload size limit in bytes.
2491 * @param int $u_bytes Maximum upload filesize in bytes.
2492 * @param int $p_bytes Maximum size of POST data in bytes.
2494 return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2498 * Returns a WP_Image_Editor instance and loads file into it.
2502 * @param string $path Path to the file to load.
2503 * @param array $args Optional. Additional arguments for retrieving the image editor.
2504 * Default empty array.
2505 * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
2508 function wp_get_image_editor( $path, $args = array() ) {
2509 $args['path'] = $path;
2511 if ( ! isset( $args['mime_type'] ) ) {
2512 $file_info = wp_check_filetype( $args['path'] );
2514 // If $file_info['type'] is false, then we let the editor attempt to
2515 // figure out the file type, rather than forcing a failure based on extension.
2516 if ( isset( $file_info ) && $file_info['type'] )
2517 $args['mime_type'] = $file_info['type'];
2520 $implementation = _wp_image_editor_choose( $args );
2522 if ( $implementation ) {
2523 $editor = new $implementation( $path );
2524 $loaded = $editor->load();
2526 if ( is_wp_error( $loaded ) )
2532 return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
2536 * Tests whether there is an editor that supports a given mime type or methods.
2540 * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
2541 * Default empty array.
2542 * @return bool True if an eligible editor is found; false otherwise.
2544 function wp_image_editor_supports( $args = array() ) {
2545 return (bool) _wp_image_editor_choose( $args );
2549 * Tests which editors are capable of supporting the request.
2554 * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
2555 * @return string|bool Class name for the first editor that claims to support the request. False if no
2556 * editor claims to support the request.
2558 function _wp_image_editor_choose( $args = array() ) {
2559 require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
2560 require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
2561 require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
2564 * Filter the list of image editing library classes.
2568 * @param array $image_editors List of available image editors. Defaults are
2569 * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
2571 $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
2573 foreach ( $implementations as $implementation ) {
2574 if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
2577 if ( isset( $args['mime_type'] ) &&
2579 array( $implementation, 'supports_mime_type' ),
2580 $args['mime_type'] ) ) {
2584 if ( isset( $args['methods'] ) &&
2585 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
2589 return $implementation;
2596 * Prints default plupload arguments.
2600 function wp_plupload_default_settings() {
2603 $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
2604 if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
2607 $max_upload_size = wp_max_upload_size();
2610 'runtimes' => 'html5,flash,silverlight,html4',
2611 'file_data_name' => 'async-upload', // key passed to $_FILE.
2612 'url' => admin_url( 'async-upload.php', 'relative' ),
2613 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
2614 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
2616 'max_file_size' => $max_upload_size . 'b',
2620 // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
2621 // when enabled. See #29602.
2622 if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
2623 strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
2625 $defaults['multi_selection'] = false;
2629 * Filter the Plupload default settings.
2633 * @param array $defaults Default Plupload settings array.
2635 $defaults = apply_filters( 'plupload_default_settings', $defaults );
2638 'action' => 'upload-attachment',
2642 * Filter the Plupload default parameters.
2646 * @param array $params Default Plupload parameters array.
2648 $params = apply_filters( 'plupload_default_params', $params );
2649 $params['_wpnonce'] = wp_create_nonce( 'media-form' );
2650 $defaults['multipart_params'] = $params;
2653 'defaults' => $defaults,
2655 'mobile' => wp_is_mobile(),
2656 'supported' => _device_can_upload(),
2658 'limitExceeded' => is_multisite() && ! is_upload_space_available()
2661 $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
2664 $script = "$data\n$script";
2666 $wp_scripts->add_data( 'wp-plupload', 'data', $script );
2670 * Prepares an attachment post object for JS, where it is expected
2671 * to be JSON-encoded and fit into an Attachment model.
2675 * @param mixed $attachment Attachment ID or object.
2676 * @return array Array of attachment details.
2678 function wp_prepare_attachment_for_js( $attachment ) {
2679 if ( ! $attachment = get_post( $attachment ) )
2682 if ( 'attachment' != $attachment->post_type )
2685 $meta = wp_get_attachment_metadata( $attachment->ID );
2686 if ( false !== strpos( $attachment->post_mime_type, '/' ) )
2687 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
2689 list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
2691 $attachment_url = wp_get_attachment_url( $attachment->ID );
2694 'id' => $attachment->ID,
2695 'title' => $attachment->post_title,
2696 'filename' => wp_basename( $attachment->guid ),
2697 'url' => $attachment_url,
2698 'link' => get_attachment_link( $attachment->ID ),
2699 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
2700 'author' => $attachment->post_author,
2701 'description' => $attachment->post_content,
2702 'caption' => $attachment->post_excerpt,
2703 'name' => $attachment->post_name,
2704 'status' => $attachment->post_status,
2705 'uploadedTo' => $attachment->post_parent,
2706 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
2707 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
2708 'menuOrder' => $attachment->menu_order,
2709 'mime' => $attachment->post_mime_type,
2711 'subtype' => $subtype,
2712 'icon' => wp_mime_type_icon( $attachment->ID ),
2713 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
2719 'editLink' => false,
2723 $author = new WP_User( $attachment->post_author );
2724 $response['authorName'] = $author->display_name;
2726 if ( $attachment->post_parent ) {
2727 $post_parent = get_post( $attachment->post_parent );
2729 $post_parent = false;
2732 if ( $post_parent ) {
2733 $parent_type = get_post_type_object( $post_parent->post_type );
2734 if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
2735 $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
2737 $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
2740 $attached_file = get_attached_file( $attachment->ID );
2741 if ( file_exists( $attached_file ) ) {
2742 $bytes = filesize( $attached_file );
2743 $response['filesizeInBytes'] = $bytes;
2744 $response['filesizeHumanReadable'] = size_format( $bytes );
2747 if ( current_user_can( 'edit_post', $attachment->ID ) ) {
2748 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
2749 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
2750 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
2753 if ( current_user_can( 'delete_post', $attachment->ID ) )
2754 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
2756 if ( $meta && 'image' === $type ) {
2759 /** This filter is documented in wp-admin/includes/media.php */
2760 $possible_sizes = apply_filters( 'image_size_names_choose', array(
2761 'thumbnail' => __('Thumbnail'),
2762 'medium' => __('Medium'),
2763 'large' => __('Large'),
2764 'full' => __('Full Size'),
2766 unset( $possible_sizes['full'] );
2768 // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
2769 // First: run the image_downsize filter. If it returns something, we can use its data.
2770 // If the filter does not return something, then image_downsize() is just an expensive
2771 // way to check the image metadata, which we do second.
2772 foreach ( $possible_sizes as $size => $label ) {
2774 /** This filter is documented in wp-includes/media.php */
2775 if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
2776 if ( ! $downsize[3] )
2778 $sizes[ $size ] = array(
2779 'height' => $downsize[2],
2780 'width' => $downsize[1],
2781 'url' => $downsize[0],
2782 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
2784 } elseif ( isset( $meta['sizes'][ $size ] ) ) {
2785 if ( ! isset( $base_url ) )
2786 $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
2788 // Nothing from the filter, so consult image metadata if we have it.
2789 $size_meta = $meta['sizes'][ $size ];
2791 // We have the actual image size, but might need to further constrain it if content_width is narrower.
2792 // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
2793 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
2795 $sizes[ $size ] = array(
2796 'height' => $height,
2798 'url' => $base_url . $size_meta['file'],
2799 'orientation' => $height > $width ? 'portrait' : 'landscape',
2804 $sizes['full'] = array( 'url' => $attachment_url );
2806 if ( isset( $meta['height'], $meta['width'] ) ) {
2807 $sizes['full']['height'] = $meta['height'];
2808 $sizes['full']['width'] = $meta['width'];
2809 $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
2812 $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
2813 } elseif ( $meta && 'video' === $type ) {
2814 if ( isset( $meta['width'] ) )
2815 $response['width'] = (int) $meta['width'];
2816 if ( isset( $meta['height'] ) )
2817 $response['height'] = (int) $meta['height'];
2820 if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
2821 if ( isset( $meta['length_formatted'] ) )
2822 $response['fileLength'] = $meta['length_formatted'];
2824 $response['meta'] = array();
2825 foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
2826 $response['meta'][ $key ] = false;
2828 if ( ! empty( $meta[ $key ] ) ) {
2829 $response['meta'][ $key ] = $meta[ $key ];
2833 $id = get_post_thumbnail_id( $attachment->ID );
2834 if ( ! empty( $id ) ) {
2835 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
2836 $response['image'] = compact( 'src', 'width', 'height' );
2837 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
2838 $response['thumb'] = compact( 'src', 'width', 'height' );
2840 $src = wp_mime_type_icon( $attachment->ID );
2843 $response['image'] = compact( 'src', 'width', 'height' );
2844 $response['thumb'] = compact( 'src', 'width', 'height' );
2848 if ( function_exists('get_compat_media_markup') )
2849 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
2852 * Filter the attachment data prepared for JavaScript.
2856 * @param array $response Array of prepared attachment data.
2857 * @param int|object $attachment Attachment ID or object.
2858 * @param array $meta Array of attachment meta data.
2860 return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
2864 * Enqueues all scripts, styles, settings, and templates necessary to use
2865 * all media JS APIs.
2869 * @param array $args {
2870 * Arguments for enqueuing media scripts.
2872 * @type int|WP_Post A post object or ID.
2874 * @return array List of media view settings.
2876 function wp_enqueue_media( $args = array() ) {
2878 // Enqueue me just once per page, please.
2879 if ( did_action( 'wp_enqueue_media' ) )
2882 global $content_width, $wpdb, $wp_locale;
2887 $args = wp_parse_args( $args, $defaults );
2889 // We're going to pass the old thickbox media tabs to `media_upload_tabs`
2890 // to ensure plugins will work. We will then unset those tabs.
2892 // handler action suffix => tab label
2899 /** This filter is documented in wp-admin/includes/media.php */
2900 $tabs = apply_filters( 'media_upload_tabs', $tabs );
2901 unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
2904 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
2905 'align' => get_option( 'image_default_align' ), // empty default
2906 'size' => get_option( 'image_default_size' ), // empty default
2909 $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
2910 $mimes = get_allowed_mime_types();
2911 $ext_mimes = array();
2912 foreach ( $exts as $ext ) {
2913 foreach ( $mimes as $ext_preg => $mime_match ) {
2914 if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
2915 $ext_mimes[ $ext ] = $mime_match;
2921 $has_audio = $wpdb->get_var( "
2924 WHERE post_type = 'attachment'
2925 AND post_mime_type LIKE 'audio%'
2928 $has_video = $wpdb->get_var( "
2931 WHERE post_type = 'attachment'
2932 AND post_mime_type LIKE 'video%'
2935 $months = $wpdb->get_results( $wpdb->prepare( "
2936 SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
2938 WHERE post_type = %s
2939 ORDER BY post_date DESC
2940 ", 'attachment' ) );
2941 foreach ( $months as $month_year ) {
2942 $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
2947 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
2948 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
2949 /** This filter is documented in wp-admin/includes/media.php */
2950 'captions' => ! apply_filters( 'disable_captions', '' ),
2952 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
2957 'defaultProps' => $props,
2958 'attachmentCounts' => array(
2959 'audio' => ( $has_audio ) ? 1 : 0,
2960 'video' => ( $has_video ) ? 1 : 0
2962 'embedExts' => $exts,
2963 'embedMimes' => $ext_mimes,
2964 'contentWidth' => $content_width,
2965 'months' => $months,
2966 'mediaTrash' => MEDIA_TRASH ? 1 : 0
2970 if ( isset( $args['post'] ) ) {
2971 $post = get_post( $args['post'] );
2972 $settings['post'] = array(
2974 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
2977 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
2978 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
2979 if ( wp_attachment_is( 'audio', $post ) ) {
2980 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
2981 } elseif ( wp_attachment_is( 'video', $post ) ) {
2982 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
2986 if ( $thumbnail_support ) {
2987 $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
2988 $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
2992 $hier = $post && is_post_type_hierarchical( $post->post_type );
2996 'url' => __( 'URL' ),
2997 'addMedia' => __( 'Add Media' ),
2998 'search' => __( 'Search' ),
2999 'select' => __( 'Select' ),
3000 'cancel' => __( 'Cancel' ),
3001 'update' => __( 'Update' ),
3002 'replace' => __( 'Replace' ),
3003 'remove' => __( 'Remove' ),
3004 'back' => __( 'Back' ),
3005 /* translators: This is a would-be plural string used in the media manager.
3006 If there is not a word you can use in your language to avoid issues with the
3007 lack of plural support here, turn it into "selected: %d" then translate it.
3009 'selected' => __( '%d selected' ),
3010 'dragInfo' => __( 'Drag and drop to reorder media files.' ),
3013 'uploadFilesTitle' => __( 'Upload Files' ),
3014 'uploadImagesTitle' => __( 'Upload Images' ),
3017 'mediaLibraryTitle' => __( 'Media Library' ),
3018 'insertMediaTitle' => __( 'Insert Media' ),
3019 'createNewGallery' => __( 'Create a new gallery' ),
3020 'createNewPlaylist' => __( 'Create a new playlist' ),
3021 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
3022 'returnToLibrary' => __( '← Return to library' ),
3023 'allMediaItems' => __( 'All media items' ),
3024 'allDates' => __( 'All dates' ),
3025 'noItemsFound' => __( 'No items found.' ),
3026 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
3027 'unattached' => __( 'Unattached' ),
3028 'trash' => _x( 'Trash', 'noun' ),
3029 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
3030 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
3031 'warnBulkDelete' => __( "You are about to permanently delete these items.\n 'Cancel' to stop, 'OK' to delete." ),
3032 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
3033 'bulkSelect' => __( 'Bulk Select' ),
3034 'cancelSelection' => __( 'Cancel Selection' ),
3035 'trashSelected' => __( 'Trash Selected' ),
3036 'untrashSelected' => __( 'Untrash Selected' ),
3037 'deleteSelected' => __( 'Delete Selected' ),
3038 'deletePermanently' => __( 'Delete Permanently' ),
3039 'apply' => __( 'Apply' ),
3040 'filterByDate' => __( 'Filter by date' ),
3041 'filterByType' => __( 'Filter by type' ),
3042 'searchMediaLabel' => __( 'Search Media' ),
3043 'noMedia' => __( 'No media attachments found.' ),
3046 'attachmentDetails' => __( 'Attachment Details' ),
3049 'insertFromUrlTitle' => __( 'Insert from URL' ),
3052 'setFeaturedImageTitle' => __( 'Set Featured Image' ),
3053 'setFeaturedImage' => __( 'Set featured image' ),
3056 'createGalleryTitle' => __( 'Create Gallery' ),
3057 'editGalleryTitle' => __( 'Edit Gallery' ),
3058 'cancelGalleryTitle' => __( '← Cancel Gallery' ),
3059 'insertGallery' => __( 'Insert gallery' ),
3060 'updateGallery' => __( 'Update gallery' ),
3061 'addToGallery' => __( 'Add to gallery' ),
3062 'addToGalleryTitle' => __( 'Add to Gallery' ),
3063 'reverseOrder' => __( 'Reverse order' ),
3066 'imageDetailsTitle' => __( 'Image Details' ),
3067 'imageReplaceTitle' => __( 'Replace Image' ),
3068 'imageDetailsCancel' => __( 'Cancel Edit' ),
3069 'editImage' => __( 'Edit Image' ),
3072 'chooseImage' => __( 'Choose Image' ),
3073 'selectAndCrop' => __( 'Select and Crop' ),
3074 'skipCropping' => __( 'Skip Cropping' ),
3075 'cropImage' => __( 'Crop Image' ),
3076 'cropYourImage' => __( 'Crop your image' ),
3077 'cropping' => __( 'Cropping…' ),
3078 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
3079 'cropError' => __( 'There has been an error cropping your image.' ),
3082 'audioDetailsTitle' => __( 'Audio Details' ),
3083 'audioReplaceTitle' => __( 'Replace Audio' ),
3084 'audioAddSourceTitle' => __( 'Add Audio Source' ),
3085 'audioDetailsCancel' => __( 'Cancel Edit' ),
3088 'videoDetailsTitle' => __( 'Video Details' ),
3089 'videoReplaceTitle' => __( 'Replace Video' ),
3090 'videoAddSourceTitle' => __( 'Add Video Source' ),
3091 'videoDetailsCancel' => __( 'Cancel Edit' ),
3092 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
3093 'videoAddTrackTitle' => __( 'Add Subtitles' ),
3096 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
3097 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
3098 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
3099 'cancelPlaylistTitle' => __( '← Cancel Audio Playlist' ),
3100 'insertPlaylist' => __( 'Insert audio playlist' ),
3101 'updatePlaylist' => __( 'Update audio playlist' ),
3102 'addToPlaylist' => __( 'Add to audio playlist' ),
3103 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
3106 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
3107 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
3108 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
3109 'cancelVideoPlaylistTitle' => __( '← Cancel Video Playlist' ),
3110 'insertVideoPlaylist' => __( 'Insert video playlist' ),
3111 'updateVideoPlaylist' => __( 'Update video playlist' ),
3112 'addToVideoPlaylist' => __( 'Add to video playlist' ),
3113 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
3117 * Filter the media view settings.
3121 * @param array $settings List of media view settings.
3122 * @param WP_Post $post Post object.
3124 $settings = apply_filters( 'media_view_settings', $settings, $post );
3127 * Filter the media view strings.
3131 * @param array $strings List of media view strings.
3132 * @param WP_Post $post Post object.
3134 $strings = apply_filters( 'media_view_strings', $strings, $post );
3136 $strings['settings'] = $settings;
3138 // Ensure we enqueue media-editor first, that way media-views is
3139 // registered internally before we try to localize it. see #24724.
3140 wp_enqueue_script( 'media-editor' );
3141 wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
3143 wp_enqueue_script( 'media-audiovideo' );
3144 wp_enqueue_style( 'media-views' );
3146 wp_enqueue_script( 'mce-view' );
3147 wp_enqueue_script( 'image-edit' );
3149 wp_enqueue_style( 'imgareaselect' );
3150 wp_plupload_default_settings();
3152 require_once ABSPATH . WPINC . '/media-template.php';
3153 add_action( 'admin_footer', 'wp_print_media_templates' );
3154 add_action( 'wp_footer', 'wp_print_media_templates' );
3155 add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
3158 * Fires at the conclusion of wp_enqueue_media().
3162 do_action( 'wp_enqueue_media' );
3166 * Retrieves media attached to the passed post.
3170 * @param string $type Mime type.
3171 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3172 * @return array Found attachments.
3174 function get_attached_media( $type, $post = 0 ) {
3175 if ( ! $post = get_post( $post ) )
3179 'post_parent' => $post->ID,
3180 'post_type' => 'attachment',
3181 'post_mime_type' => $type,
3182 'posts_per_page' => -1,
3183 'orderby' => 'menu_order',
3188 * Filter arguments used to retrieve media attached to the given post.
3192 * @param array $args Post query arguments.
3193 * @param string $type Mime type of the desired media.
3194 * @param mixed $post Post ID or object.
3196 $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
3198 $children = get_children( $args );
3201 * Filter the list of media attached to the given post.
3205 * @param array $children Associative array of media attached to the given post.
3206 * @param string $type Mime type of the media desired.
3207 * @param mixed $post Post ID or object.
3209 return (array) apply_filters( 'get_attached_media', $children, $type, $post );
3213 * Check the content blob for an audio, video, object, embed, or iframe tags.
3217 * @param string $content A string which might contain media data.
3218 * @param array $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
3219 * @return array A list of found HTML media embeds.
3221 function get_media_embedded_in_content( $content, $types = null ) {
3225 * Filter the embedded media types that are allowed to be returned from the content blob.
3229 * @param array $allowed_media_types An array of allowed media types. Default media types are
3230 * 'audio', 'video', 'object', 'embed', and 'iframe'.
3232 $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
3234 if ( ! empty( $types ) ) {
3235 if ( ! is_array( $types ) ) {
3236 $types = array( $types );
3239 $allowed_media_types = array_intersect( $allowed_media_types, $types );
3242 $tags = implode( '|', $allowed_media_types );
3244 if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
3245 foreach ( $matches[0] as $match ) {
3254 * Retrieves galleries from the passed post's content.
3258 * @param int|WP_Post $post Post ID or object.
3259 * @param bool $html Optional. Whether to return HTML or data in the array. Default true.
3260 * @return array A list of arrays, each containing gallery data and srcs parsed
3261 * from the expanded shortcode.
3263 function get_post_galleries( $post, $html = true ) {
3264 if ( ! $post = get_post( $post ) )
3267 if ( ! has_shortcode( $post->post_content, 'gallery' ) )
3270 $galleries = array();
3271 if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
3272 foreach ( $matches as $shortcode ) {
3273 if ( 'gallery' === $shortcode[2] ) {
3276 $gallery = do_shortcode_tag( $shortcode );
3278 $galleries[] = $gallery;
3280 preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
3281 if ( ! empty( $src ) ) {
3282 foreach ( $src as $s )
3286 $data = shortcode_parse_atts( $shortcode[3] );
3287 $data['src'] = array_values( array_unique( $srcs ) );
3288 $galleries[] = $data;
3295 * Filter the list of all found galleries in the given post.
3299 * @param array $galleries Associative array of all found post galleries.
3300 * @param WP_Post $post Post object.
3302 return apply_filters( 'get_post_galleries', $galleries, $post );
3306 * Check a specified post's content for gallery and, if present, return the first
3310 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3311 * @param bool $html Optional. Whether to return HTML or data. Default is true.
3312 * @return string|array Gallery data and srcs parsed from the expanded shortcode.
3314 function get_post_gallery( $post = 0, $html = true ) {
3315 $galleries = get_post_galleries( $post, $html );
3316 $gallery = reset( $galleries );
3319 * Filter the first-found post gallery.
3323 * @param array $gallery The first-found post gallery.
3324 * @param int|WP_Post $post Post ID or object.
3325 * @param array $galleries Associative array of all found post galleries.
3327 return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
3331 * Retrieve the image srcs from galleries from a post's content, if present
3335 * @see get_post_galleries()
3337 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3338 * @return array A list of lists, each containing image srcs parsed.
3339 * from an expanded shortcode
3341 function get_post_galleries_images( $post = 0 ) {
3342 $galleries = get_post_galleries( $post, false );
3343 return wp_list_pluck( $galleries, 'src' );
3347 * Checks a post's content for galleries and return the image srcs for the first found gallery
3351 * @see get_post_gallery()
3353 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3354 * @return array A list of a gallery's image srcs in order.
3356 function get_post_gallery_images( $post = 0 ) {
3357 $gallery = get_post_gallery( $post, false );
3358 return empty( $gallery['src'] ) ? array() : $gallery['src'];
3362 * Maybe attempts to generate attachment metadata, if missing.
3366 * @param WP_Post $attachment Attachment object.
3368 function wp_maybe_generate_attachment_metadata( $attachment ) {
3369 if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
3373 $file = get_attached_file( $attachment_id );
3374 $meta = wp_get_attachment_metadata( $attachment_id );
3375 if ( empty( $meta ) && file_exists( $file ) ) {
3376 $_meta = get_post_meta( $attachment_id );
3377 $regeneration_lock = 'wp_generating_att_' . $attachment_id;
3378 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
3379 set_transient( $regeneration_lock, $file );
3380 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
3381 delete_transient( $regeneration_lock );
3387 * Tries to convert an attachment URL into a post ID.
3391 * @global wpdb $wpdb WordPress database abstraction object.
3393 * @param string $url The URL to resolve.
3394 * @return int The found post ID, or 0 on failure.
3396 function attachment_url_to_postid( $url ) {
3399 $dir = wp_upload_dir();
3402 if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
3403 $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
3406 $sql = $wpdb->prepare(
3407 "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
3410 $post_id = $wpdb->get_var( $sql );
3413 * Filter an attachment id found by URL.
3417 * @param int|null $post_id The post_id (if any) found by the function.
3418 * @param string $url The URL being looked up.
3420 $post_id = apply_filters( 'attachment_url_to_postid', $post_id, $url );
3422 return (int) $post_id;
3426 * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
3430 * @global $wp_version
3432 * @return array The relevant CSS file URLs.
3434 function wpview_media_sandbox_styles() {
3435 $version = 'ver=' . $GLOBALS['wp_version'];
3436 $mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
3437 $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
3439 return array( $mediaelement, $wpmediaelement );