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] );
850 } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
851 $attr['caption'] = wp_kses( $attr['caption'], 'post' );
855 * Filter the default caption shortcode output.
857 * If the filtered output isn't empty, it will be used instead of generating
858 * the default caption template.
862 * @see img_caption_shortcode()
864 * @param string $output The caption output. Default empty.
865 * @param array $attr Attributes of the caption shortcode.
866 * @param string $content The image element, possibly wrapped in a hyperlink.
868 $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
872 $atts = shortcode_atts( array(
874 'align' => 'alignnone',
878 ), $attr, 'caption' );
880 $atts['width'] = (int) $atts['width'];
881 if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
884 if ( ! empty( $atts['id'] ) )
885 $atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';
887 $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
889 if ( current_theme_supports( 'html5', 'caption' ) ) {
890 return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
891 . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
894 $caption_width = 10 + $atts['width'];
897 * Filter the width of an image's caption.
899 * By default, the caption is 10 pixels greater than the width of the image,
900 * to prevent post content from running up against a floated image.
904 * @see img_caption_shortcode()
906 * @param int $caption_width Width of the caption in pixels. To remove this inline style,
908 * @param array $atts Attributes of the caption shortcode.
909 * @param string $content The image element, possibly wrapped in a hyperlink.
911 $caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
914 if ( $caption_width )
915 $style = 'style="width: ' . (int) $caption_width . 'px" ';
917 return '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
918 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
921 add_shortcode('gallery', 'gallery_shortcode');
924 * Builds the Gallery shortcode output.
926 * This implements the functionality of the Gallery Shortcode for displaying
927 * WordPress images on a post.
931 * @param array $attr {
932 * Attributes of the gallery shortcode.
934 * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
935 * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
936 * Accepts any valid SQL ORDERBY statement.
937 * @type int $id Post ID.
938 * @type string $itemtag HTML tag to use for each image in the gallery.
939 * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
940 * @type string $icontag HTML tag to use for each image's icon.
941 * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
942 * @type string $captiontag HTML tag to use for each image's caption.
943 * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
944 * @type int $columns Number of columns of images to display. Default 3.
945 * @type string $size Size of the images to display. Default 'thumbnail'.
946 * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
947 * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
948 * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
949 * @type string $link What to link each image to. Default empty (links to the attachment page).
950 * Accepts 'file', 'none'.
952 * @return string HTML content to display gallery.
954 function gallery_shortcode( $attr ) {
957 static $instance = 0;
960 if ( ! empty( $attr['ids'] ) ) {
961 // 'ids' is explicitly ordered, unless you specify otherwise.
962 if ( empty( $attr['orderby'] ) ) {
963 $attr['orderby'] = 'post__in';
965 $attr['include'] = $attr['ids'];
969 * Filter the default gallery shortcode output.
971 * If the filtered output isn't empty, it will be used instead of generating
972 * the default gallery template.
975 * @since 4.2.0 The `$instance` parameter was added.
977 * @see gallery_shortcode()
979 * @param string $output The gallery output. Default empty.
980 * @param array $attr Attributes of the gallery shortcode.
981 * @param int $instance Unique numeric ID of this gallery shortcode instance.
983 $output = apply_filters( 'post_gallery', '', $attr, $instance );
984 if ( $output != '' ) {
988 $html5 = current_theme_supports( 'html5', 'gallery' );
989 $atts = shortcode_atts( array(
991 'orderby' => 'menu_order ID',
992 'id' => $post ? $post->ID : 0,
993 'itemtag' => $html5 ? 'figure' : 'dl',
994 'icontag' => $html5 ? 'div' : 'dt',
995 'captiontag' => $html5 ? 'figcaption' : 'dd',
997 'size' => 'thumbnail',
1001 ), $attr, 'gallery' );
1003 $id = intval( $atts['id'] );
1005 if ( ! empty( $atts['include'] ) ) {
1006 $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1008 $attachments = array();
1009 foreach ( $_attachments as $key => $val ) {
1010 $attachments[$val->ID] = $_attachments[$key];
1012 } elseif ( ! empty( $atts['exclude'] ) ) {
1013 $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'] ) );
1015 $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1018 if ( empty( $attachments ) ) {
1024 foreach ( $attachments as $att_id => $attachment ) {
1025 $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
1030 $itemtag = tag_escape( $atts['itemtag'] );
1031 $captiontag = tag_escape( $atts['captiontag'] );
1032 $icontag = tag_escape( $atts['icontag'] );
1033 $valid_tags = wp_kses_allowed_html( 'post' );
1034 if ( ! isset( $valid_tags[ $itemtag ] ) ) {
1037 if ( ! isset( $valid_tags[ $captiontag ] ) ) {
1040 if ( ! isset( $valid_tags[ $icontag ] ) ) {
1044 $columns = intval( $atts['columns'] );
1045 $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
1046 $float = is_rtl() ? 'right' : 'left';
1048 $selector = "gallery-{$instance}";
1050 $gallery_style = '';
1053 * Filter whether to print default gallery styles.
1057 * @param bool $print Whether to print default gallery styles.
1058 * Defaults to false if the theme supports HTML5 galleries.
1059 * Otherwise, defaults to true.
1061 if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1063 <style type='text/css'>
1067 #{$selector} .gallery-item {
1071 width: {$itemwidth}%;
1074 border: 2px solid #cfcfcf;
1076 #{$selector} .gallery-caption {
1079 /* see gallery_shortcode() in wp-includes/media.php */
1083 $size_class = sanitize_html_class( $atts['size'] );
1084 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1087 * Filter the default gallery shortcode CSS styles.
1091 * @param string $gallery_style Default CSS styles and opening HTML div container
1092 * for the gallery shortcode output.
1094 $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1097 foreach ( $attachments as $id => $attachment ) {
1099 $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
1100 if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
1101 $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
1102 } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
1103 $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
1105 $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
1107 $image_meta = wp_get_attachment_metadata( $id );
1110 if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
1111 $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1113 $output .= "<{$itemtag} class='gallery-item'>";
1115 <{$icontag} class='gallery-icon {$orientation}'>
1118 if ( $captiontag && trim($attachment->post_excerpt) ) {
1120 <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
1121 " . wptexturize($attachment->post_excerpt) . "
1124 $output .= "</{$itemtag}>";
1125 if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1126 $output .= '<br style="clear: both" />';
1130 if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1132 <br style='clear: both' />";
1142 * Outputs the templates used by playlists.
1146 function wp_underscore_playlist_templates() {
1148 <script type="text/html" id="tmpl-wp-playlist-current-item">
1149 <# if ( data.image ) { #>
1150 <img src="{{ data.thumb.src }}"/>
1152 <div class="wp-playlist-caption">
1153 <span class="wp-playlist-item-meta wp-playlist-item-title">“{{ data.title }}”</span>
1154 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1155 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1158 <script type="text/html" id="tmpl-wp-playlist-item">
1159 <div class="wp-playlist-item">
1160 <a class="wp-playlist-caption" href="{{ data.src }}">
1161 {{ data.index ? ( data.index + '. ' ) : '' }}
1162 <# if ( data.caption ) { #>
1165 <span class="wp-playlist-item-title">“{{{ data.title }}}”</span>
1166 <# if ( data.artists && data.meta.artist ) { #>
1167 <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span>
1171 <# if ( data.meta.length_formatted ) { #>
1172 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1180 * Outputs and enqueue default scripts and styles for playlists.
1184 * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1186 function wp_playlist_scripts( $type ) {
1187 wp_enqueue_style( 'wp-mediaelement' );
1188 wp_enqueue_script( 'wp-playlist' );
1190 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1192 add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1193 add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1197 * Builds the Playlist shortcode output.
1199 * This implements the functionality of the playlist shortcode for displaying
1200 * a collection of WordPress audio or video files in a post.
1204 * @param array $attr {
1205 * Array of default playlist attributes.
1207 * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
1208 * @type string $order Designates ascending or descending order of items in the playlist.
1209 * Accepts 'ASC', 'DESC'. Default 'ASC'.
1210 * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
1211 * passed, this defaults to the order of the $ids array ('post__in').
1212 * Otherwise default is 'menu_order ID'.
1213 * @type int $id If an explicit $ids array is not present, this parameter
1214 * will determine which attachments are used for the playlist.
1215 * Default is the current post ID.
1216 * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
1217 * a playlist will be created from all $type attachments of $id.
1219 * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
1220 * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
1221 * @type bool $tracklist Whether to show or hide the playlist. Default true.
1222 * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
1223 * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
1224 * thumbnail). Default true.
1225 * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
1228 * @return string Playlist output. Empty string if the passed type is unsupported.
1230 function wp_playlist_shortcode( $attr ) {
1231 global $content_width;
1234 static $instance = 0;
1237 if ( ! empty( $attr['ids'] ) ) {
1238 // 'ids' is explicitly ordered, unless you specify otherwise.
1239 if ( empty( $attr['orderby'] ) ) {
1240 $attr['orderby'] = 'post__in';
1242 $attr['include'] = $attr['ids'];
1246 * Filter the playlist output.
1248 * Passing a non-empty value to the filter will short-circuit generation
1249 * of the default playlist output, returning the passed value instead.
1252 * @since 4.2.0 The `$instance` parameter was added.
1254 * @param string $output Playlist output. Default empty.
1255 * @param array $attr An array of shortcode attributes.
1256 * @param int $instance Unique numeric ID of this playlist shortcode instance.
1258 $output = apply_filters( 'post_playlist', '', $attr, $instance );
1259 if ( $output != '' ) {
1263 $atts = shortcode_atts( array(
1266 'orderby' => 'menu_order ID',
1267 'id' => $post ? $post->ID : 0,
1271 'tracklist' => true,
1272 'tracknumbers' => true,
1275 ), $attr, 'playlist' );
1277 $id = intval( $atts['id'] );
1279 if ( $atts['type'] !== 'audio' ) {
1280 $atts['type'] = 'video';
1284 'post_status' => 'inherit',
1285 'post_type' => 'attachment',
1286 'post_mime_type' => $atts['type'],
1287 'order' => $atts['order'],
1288 'orderby' => $atts['orderby']
1291 if ( ! empty( $atts['include'] ) ) {
1292 $args['include'] = $atts['include'];
1293 $_attachments = get_posts( $args );
1295 $attachments = array();
1296 foreach ( $_attachments as $key => $val ) {
1297 $attachments[$val->ID] = $_attachments[$key];
1299 } elseif ( ! empty( $atts['exclude'] ) ) {
1300 $args['post_parent'] = $id;
1301 $args['exclude'] = $atts['exclude'];
1302 $attachments = get_children( $args );
1304 $args['post_parent'] = $id;
1305 $attachments = get_children( $args );
1308 if ( empty( $attachments ) ) {
1314 foreach ( $attachments as $att_id => $attachment ) {
1315 $output .= wp_get_attachment_link( $att_id ) . "\n";
1320 $outer = 22; // default padding and border of wrapper
1322 $default_width = 640;
1323 $default_height = 360;
1325 $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
1326 $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
1329 'type' => $atts['type'],
1330 // don't pass strings to JSON, will be truthy in JS
1331 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
1332 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
1333 'images' => wp_validate_boolean( $atts['images'] ),
1334 'artists' => wp_validate_boolean( $atts['artists'] ),
1338 foreach ( $attachments as $attachment ) {
1339 $url = wp_get_attachment_url( $attachment->ID );
1340 $ftype = wp_check_filetype( $url, wp_get_mime_types() );
1343 'type' => $ftype['type'],
1344 'title' => $attachment->post_title,
1345 'caption' => $attachment->post_excerpt,
1346 'description' => $attachment->post_content
1349 $track['meta'] = array();
1350 $meta = wp_get_attachment_metadata( $attachment->ID );
1351 if ( ! empty( $meta ) ) {
1353 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
1354 if ( ! empty( $meta[ $key ] ) ) {
1355 $track['meta'][ $key ] = $meta[ $key ];
1359 if ( 'video' === $atts['type'] ) {
1360 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1361 $width = $meta['width'];
1362 $height = $meta['height'];
1363 $theme_height = round( ( $height * $theme_width ) / $width );
1365 $width = $default_width;
1366 $height = $default_height;
1369 $track['dimensions'] = array(
1370 'original' => compact( 'width', 'height' ),
1372 'width' => $theme_width,
1373 'height' => $theme_height
1379 if ( $atts['images'] ) {
1380 $thumb_id = get_post_thumbnail_id( $attachment->ID );
1381 if ( ! empty( $thumb_id ) ) {
1382 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
1383 $track['image'] = compact( 'src', 'width', 'height' );
1384 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
1385 $track['thumb'] = compact( 'src', 'width', 'height' );
1387 $src = wp_mime_type_icon( $attachment->ID );
1390 $track['image'] = compact( 'src', 'width', 'height' );
1391 $track['thumb'] = compact( 'src', 'width', 'height' );
1397 $data['tracks'] = $tracks;
1399 $safe_type = esc_attr( $atts['type'] );
1400 $safe_style = esc_attr( $atts['style'] );
1404 if ( 1 === $instance ) {
1406 * Print and enqueue playlist scripts, styles, and JavaScript templates.
1410 * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
1411 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
1413 do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
1415 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
1416 <?php if ( 'audio' === $atts['type'] ): ?>
1417 <div class="wp-playlist-current-item"></div>
1419 <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
1420 echo (int) $theme_width;
1421 ?>"<?php if ( 'video' === $safe_type ):
1422 echo ' height="', (int) $theme_height, '"';
1424 echo ' style="visibility: hidden"';
1425 endif; ?>></<?php echo $safe_type ?>>
1426 <div class="wp-playlist-next"></div>
1427 <div class="wp-playlist-prev"></div>
1430 foreach ( $attachments as $att_id => $attachment ) {
1431 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
1435 <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
1438 return ob_get_clean();
1440 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
1443 * Provides a No-JS Flash fallback as a last resort for audio / video.
1447 * @param string $url The media element URL.
1448 * @return string Fallback HTML.
1450 function wp_mediaelement_fallback( $url ) {
1452 * Filter the Mediaelement fallback output for no-JS.
1456 * @param string $output Fallback output for no-JS.
1457 * @param string $url Media file URL.
1459 return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
1463 * Returns a filtered list of WP-supported audio formats.
1467 * @return array Supported audio formats.
1469 function wp_get_audio_extensions() {
1471 * Filter the list of supported audio formats.
1475 * @param array $extensions An array of support audio formats. Defaults are
1476 * 'mp3', 'ogg', 'wma', 'm4a', 'wav'.
1478 return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
1482 * Returns useful keys to use to lookup data from an attachment's stored metadata.
1486 * @param WP_Post $attachment The current attachment, provided for context.
1487 * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'.
1488 * @return array Key/value pairs of field keys to labels.
1490 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
1492 'artist' => __( 'Artist' ),
1493 'album' => __( 'Album' ),
1496 if ( 'display' === $context ) {
1497 $fields['genre'] = __( 'Genre' );
1498 $fields['year'] = __( 'Year' );
1499 $fields['length_formatted'] = _x( 'Length', 'video or audio' );
1500 } elseif ( 'js' === $context ) {
1501 $fields['bitrate'] = __( 'Bitrate' );
1502 $fields['bitrate_mode'] = __( 'Bitrate Mode' );
1506 * Filter the editable list of keys to look up data from an attachment's metadata.
1510 * @param array $fields Key/value pairs of field keys to labels.
1511 * @param WP_Post $attachment Attachment object.
1512 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
1514 return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
1517 * Builds the Audio shortcode output.
1519 * This implements the functionality of the Audio Shortcode for displaying
1520 * WordPress mp3s in a post.
1524 * @param array $attr {
1525 * Attributes of the audio shortcode.
1527 * @type string $src URL to the source of the audio file. Default empty.
1528 * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
1529 * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
1530 * @type string $preload The 'preload' attribute for the `<audio>` element. Default empty.
1531 * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
1532 * @type string $id The 'id' attribute for the `<audio>` element. Default 'audio-{$post_id}-{$instance}'.
1533 * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
1535 * @param string $content Shortcode content.
1536 * @return string HTML content to display audio.
1538 function wp_audio_shortcode( $attr, $content = '' ) {
1539 $post_id = get_post() ? get_the_ID() : 0;
1541 static $instance = 0;
1545 * Filter the default audio shortcode output.
1547 * If the filtered output isn't empty, it will be used instead of generating the default audio template.
1551 * @param string $html Empty variable to be replaced with shortcode markup.
1552 * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
1553 * @param string $content Shortcode content.
1554 * @param int $instance Unique numeric ID of this audio shortcode instance.
1556 $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
1557 if ( '' !== $override ) {
1563 $default_types = wp_get_audio_extensions();
1564 $defaults_atts = array(
1570 foreach ( $default_types as $type ) {
1571 $defaults_atts[$type] = '';
1574 $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
1577 if ( ! empty( $atts['src'] ) ) {
1578 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
1579 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1580 return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
1583 array_unshift( $default_types, 'src' );
1585 foreach ( $default_types as $ext ) {
1586 if ( ! empty( $atts[ $ext ] ) ) {
1587 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
1588 if ( strtolower( $type['ext'] ) === $ext ) {
1596 $audios = get_attached_media( 'audio', $post_id );
1597 if ( empty( $audios ) ) {
1601 $audio = reset( $audios );
1602 $atts['src'] = wp_get_attachment_url( $audio->ID );
1603 if ( empty( $atts['src'] ) ) {
1607 array_unshift( $default_types, 'src' );
1611 * Filter the media library used for the audio shortcode.
1615 * @param string $library Media library used for the audio shortcode.
1617 $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
1618 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1619 wp_enqueue_style( 'wp-mediaelement' );
1620 wp_enqueue_script( 'wp-mediaelement' );
1624 * Filter the class attribute for the audio shortcode output container.
1628 * @param string $class CSS class or list of space-separated classes.
1631 'class' => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
1632 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
1633 'loop' => wp_validate_boolean( $atts['loop'] ),
1634 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
1635 'preload' => $atts['preload'],
1636 'style' => 'width: 100%; visibility: hidden;',
1639 // These ones should just be omitted altogether if they are blank
1640 foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
1641 if ( empty( $html_atts[$a] ) ) {
1642 unset( $html_atts[$a] );
1646 $attr_strings = array();
1647 foreach ( $html_atts as $k => $v ) {
1648 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1652 if ( 'mediaelement' === $library && 1 === $instance ) {
1653 $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
1655 $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
1658 $source = '<source type="%s" src="%s" />';
1659 foreach ( $default_types as $fallback ) {
1660 if ( ! empty( $atts[ $fallback ] ) ) {
1661 if ( empty( $fileurl ) ) {
1662 $fileurl = $atts[ $fallback ];
1664 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
1665 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
1666 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1670 if ( 'mediaelement' === $library ) {
1671 $html .= wp_mediaelement_fallback( $fileurl );
1673 $html .= '</audio>';
1676 * Filter the audio shortcode output.
1680 * @param string $html Audio shortcode HTML output.
1681 * @param array $atts Array of audio shortcode attributes.
1682 * @param string $audio Audio file.
1683 * @param int $post_id Post ID.
1684 * @param string $library Media library used for the audio shortcode.
1686 return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
1688 add_shortcode( 'audio', 'wp_audio_shortcode' );
1691 * Returns a filtered list of WP-supported video formats.
1695 * @return array List of supported video formats.
1697 function wp_get_video_extensions() {
1699 * Filter the list of supported video formats.
1703 * @param array $extensions An array of support video formats. Defaults are
1704 * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
1706 return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
1710 * Builds the Video shortcode output.
1712 * This implements the functionality of the Video Shortcode for displaying
1713 * WordPress mp4s in a post.
1717 * @param array $attr {
1718 * Attributes of the shortcode.
1720 * @type string $src URL to the source of the video file. Default empty.
1721 * @type int $height Height of the video embed in pixels. Default 360.
1722 * @type int $width Width of the video embed in pixels. Default $content_width or 640.
1723 * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
1724 * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
1725 * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
1726 * @type string $preload The 'preload' attribute for the `<video>` element.
1727 * Default 'metadata'.
1728 * @type string $class The 'class' attribute for the `<video>` element.
1729 * Default 'wp-video-shortcode'.
1730 * @type string $id The 'id' attribute for the `<video>` element.
1731 * Default 'video-{$post_id}-{$instance}'.
1733 * @param string $content Shortcode content.
1734 * @return string HTML content to display video.
1736 function wp_video_shortcode( $attr, $content = '' ) {
1737 global $content_width;
1738 $post_id = get_post() ? get_the_ID() : 0;
1740 static $instance = 0;
1744 * Filter the default video shortcode output.
1746 * If the filtered output isn't empty, it will be used instead of generating
1747 * the default video template.
1751 * @see wp_video_shortcode()
1753 * @param string $html Empty variable to be replaced with shortcode markup.
1754 * @param array $attr Attributes of the video shortcode.
1755 * @param string $content Video shortcode content.
1756 * @param int $instance Unique numeric ID of this video shortcode instance.
1758 $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
1759 if ( '' !== $override ) {
1765 $default_types = wp_get_video_extensions();
1766 $defaults_atts = array(
1771 'preload' => 'metadata',
1776 foreach ( $default_types as $type ) {
1777 $defaults_atts[$type] = '';
1780 $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
1783 // shrink the video so it isn't huge in the admin
1784 if ( $atts['width'] > $defaults_atts['width'] ) {
1785 $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
1786 $atts['width'] = $defaults_atts['width'];
1789 // if the video is bigger than the theme
1790 if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
1791 $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
1792 $atts['width'] = $content_width;
1796 $is_vimeo = $is_youtube = false;
1797 $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
1798 $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
1801 if ( ! empty( $atts['src'] ) ) {
1802 $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
1803 $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
1804 if ( ! $is_youtube && ! $is_vimeo ) {
1805 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
1806 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1807 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
1812 wp_enqueue_script( 'froogaloop' );
1816 array_unshift( $default_types, 'src' );
1818 foreach ( $default_types as $ext ) {
1819 if ( ! empty( $atts[ $ext ] ) ) {
1820 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
1821 if ( strtolower( $type['ext'] ) === $ext ) {
1829 $videos = get_attached_media( 'video', $post_id );
1830 if ( empty( $videos ) ) {
1834 $video = reset( $videos );
1835 $atts['src'] = wp_get_attachment_url( $video->ID );
1836 if ( empty( $atts['src'] ) ) {
1840 array_unshift( $default_types, 'src' );
1844 * Filter the media library used for the video shortcode.
1848 * @param string $library Media library used for the video shortcode.
1850 $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
1851 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1852 wp_enqueue_style( 'wp-mediaelement' );
1853 wp_enqueue_script( 'wp-mediaelement' );
1857 * Filter the class attribute for the video shortcode output container.
1861 * @param string $class CSS class or list of space-separated classes.
1864 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
1865 'id' => sprintf( 'video-%d-%d', $post_id, $instance ),
1866 'width' => absint( $atts['width'] ),
1867 'height' => absint( $atts['height'] ),
1868 'poster' => esc_url( $atts['poster'] ),
1869 'loop' => wp_validate_boolean( $atts['loop'] ),
1870 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
1871 'preload' => $atts['preload'],
1874 // These ones should just be omitted altogether if they are blank
1875 foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
1876 if ( empty( $html_atts[$a] ) ) {
1877 unset( $html_atts[$a] );
1881 $attr_strings = array();
1882 foreach ( $html_atts as $k => $v ) {
1883 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1887 if ( 'mediaelement' === $library && 1 === $instance ) {
1888 $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
1890 $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
1893 $source = '<source type="%s" src="%s" />';
1894 foreach ( $default_types as $fallback ) {
1895 if ( ! empty( $atts[ $fallback ] ) ) {
1896 if ( empty( $fileurl ) ) {
1897 $fileurl = $atts[ $fallback ];
1899 if ( 'src' === $fallback && $is_youtube ) {
1900 $type = array( 'type' => 'video/youtube' );
1901 } elseif ( 'src' === $fallback && $is_vimeo ) {
1902 $type = array( 'type' => 'video/vimeo' );
1904 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
1906 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
1907 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1911 if ( ! empty( $content ) ) {
1912 if ( false !== strpos( $content, "\n" ) ) {
1913 $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
1915 $html .= trim( $content );
1918 if ( 'mediaelement' === $library ) {
1919 $html .= wp_mediaelement_fallback( $fileurl );
1921 $html .= '</video>';
1924 if ( ! empty( $atts['width'] ) ) {
1925 $width_rule = sprintf( 'width: %dpx; ', $atts['width'] );
1927 $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
1930 * Filter the output of the video shortcode.
1934 * @param string $output Video shortcode HTML output.
1935 * @param array $atts Array of video shortcode attributes.
1936 * @param string $video Video file.
1937 * @param int $post_id Post ID.
1938 * @param string $library Media library used for the video shortcode.
1940 return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
1942 add_shortcode( 'video', 'wp_video_shortcode' );
1945 * Displays previous image link that has the same post parent.
1949 * @see adjacent_image_link()
1951 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
1952 * 0 or 'none' will default to 'post_title' or `$text`. Default 'thumbnail'.
1953 * @param string $text Optional. Link text. Default false.
1954 * @return string HTML output for the previous image link.
1956 function previous_image_link( $size = 'thumbnail', $text = false ) {
1957 adjacent_image_link(true, $size, $text);
1961 * Displays next image link that has the same post parent.
1965 * @see adjacent_image_link()
1967 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
1968 * 0 or 'none' will default to 'post_title' or `$text`. Default 'thumbnail'.
1969 * @param string $text Optional. Link text. Default false.
1970 * @return string HTML output for the next image link.
1972 function next_image_link($size = 'thumbnail', $text = false) {
1973 adjacent_image_link(false, $size, $text);
1977 * Displays next or previous image link that has the same post parent.
1979 * Retrieves the current attachment object from the $post global.
1983 * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
1984 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
1985 * Default 'thumbnail'.
1986 * @param bool $text Optional. Link text. Default false.
1987 * @return string The adjacent image link.
1989 function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
1991 $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' ) ) );
1993 foreach ( $attachments as $k => $attachment ) {
1994 if ( $attachment->ID == $post->ID ) {
2002 if ( $attachments ) {
2003 $k = $prev ? $k - 1 : $k + 1;
2005 if ( isset( $attachments[ $k ] ) ) {
2006 $attachment_id = $attachments[ $k ]->ID;
2007 $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
2011 $adjacent = $prev ? 'previous' : 'next';
2014 * Filter the adjacent image link.
2016 * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
2017 * either 'next', or 'previous'.
2021 * @param string $output Adjacent image HTML markup.
2022 * @param int $attachment_id Attachment ID
2023 * @param string $size Image size.
2024 * @param string $text Link text.
2026 echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
2030 * Retrieves taxonomies attached to given the attachment.
2034 * @param int|array|object $attachment Attachment ID, data array, or data object.
2035 * @return array Empty array on failure. List of taxonomies on success.
2037 function get_attachment_taxonomies( $attachment ) {
2038 if ( is_int( $attachment ) ) {
2039 $attachment = get_post( $attachment );
2040 } elseif ( is_array( $attachment ) ) {
2041 $attachment = (object) $attachment;
2043 if ( ! is_object($attachment) )
2046 $filename = basename($attachment->guid);
2048 $objects = array('attachment');
2050 if ( false !== strpos($filename, '.') )
2051 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
2052 if ( !empty($attachment->post_mime_type) ) {
2053 $objects[] = 'attachment:' . $attachment->post_mime_type;
2054 if ( false !== strpos($attachment->post_mime_type, '/') )
2055 foreach ( explode('/', $attachment->post_mime_type) as $token )
2056 if ( !empty($token) )
2057 $objects[] = "attachment:$token";
2060 $taxonomies = array();
2061 foreach ( $objects as $object )
2062 if ( $taxes = get_object_taxonomies($object) )
2063 $taxonomies = array_merge($taxonomies, $taxes);
2065 return array_unique($taxonomies);
2069 * Retrieves all of the taxonomy names that are registered for attachments.
2071 * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
2075 * @see get_taxonomies()
2077 * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
2079 * @return array The names of all taxonomy of $object_type.
2081 function get_taxonomies_for_attachments( $output = 'names' ) {
2082 $taxonomies = array();
2083 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
2084 foreach ( $taxonomy->object_type as $object_type ) {
2085 if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
2086 if ( 'names' == $output )
2087 $taxonomies[] = $taxonomy->name;
2089 $taxonomies[ $taxonomy->name ] = $taxonomy;
2099 * Create new GD image resource with transparency support
2101 * @todo: Deprecate if possible.
2105 * @param int $width Image width in pixels.
2106 * @param int $height Image height in pixels..
2107 * @return resource The GD image resource.
2109 function wp_imagecreatetruecolor($width, $height) {
2110 $img = imagecreatetruecolor($width, $height);
2111 if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
2112 imagealphablending($img, false);
2113 imagesavealpha($img, true);
2119 * Registers an embed handler.
2121 * Should probably only be used for sites that do not support oEmbed.
2125 * @see WP_Embed::register_handler()
2127 * @param string $id An internal ID/name for the handler. Needs to be unique.
2128 * @param string $regex The regex that will be used to see if this handler should be used for a URL.
2129 * @param callback $callback The callback function that will be called if the regex is matched.
2130 * @param int $priority Optional. Used to specify the order in which the registered handlers will
2131 * be tested. Default 10.
2133 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
2135 $wp_embed->register_handler( $id, $regex, $callback, $priority );
2139 * Unregisters a previously-registered embed handler.
2143 * @see WP_Embed::unregister_handler()
2145 * @param string $id The handler ID that should be removed.
2146 * @param int $priority Optional. The priority of the handler to be removed. Default 10.
2148 function wp_embed_unregister_handler( $id, $priority = 10 ) {
2150 $wp_embed->unregister_handler( $id, $priority );
2154 * Create default array of embed parameters.
2156 * The width defaults to the content width as specified by the theme. If the
2157 * theme does not specify a content width, then 500px is used.
2159 * The default height is 1.5 times the width, or 1000px, whichever is smaller.
2161 * The 'embed_defaults' filter can be used to adjust either of these values.
2165 * @param string $url Optional. The URL that should be embedded. Default empty.
2167 * @return array Default embed parameters.
2169 function wp_embed_defaults( $url = '' ) {
2170 if ( ! empty( $GLOBALS['content_width'] ) )
2171 $width = (int) $GLOBALS['content_width'];
2173 if ( empty( $width ) )
2176 $height = min( ceil( $width * 1.5 ), 1000 );
2179 * Filter the default array of embed dimensions.
2183 * @param int $width Width of the embed in pixels.
2184 * @param int $height Height of the embed in pixels.
2185 * @param string $url The URL that should be embedded.
2187 return apply_filters( 'embed_defaults', compact( 'width', 'height' ), $url );
2191 * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
2195 * @see wp_constrain_dimensions()
2197 * @param int $example_width The width of an example embed.
2198 * @param int $example_height The height of an example embed.
2199 * @param int $max_width The maximum allowed width.
2200 * @param int $max_height The maximum allowed height.
2201 * @return array The maximum possible width and height based on the example ratio.
2203 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
2204 $example_width = (int) $example_width;
2205 $example_height = (int) $example_height;
2206 $max_width = (int) $max_width;
2207 $max_height = (int) $max_height;
2209 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
2213 * Attempts to fetch the embed HTML for a provided URL using oEmbed.
2219 * @param string $url The URL that should be embedded.
2220 * @param array $args Optional. Additional arguments and parameters for retrieving embed HTML.
2222 * @return false|string False on failure or the embed HTML on success.
2224 function wp_oembed_get( $url, $args = '' ) {
2225 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2226 $oembed = _wp_oembed_get_object();
2227 return $oembed->get_html( $url, $args );
2231 * Adds a URL format and oEmbed provider URL pair.
2237 * @param string $format The format of URL that this provider can handle. You can use asterisks
2239 * @param string $provider The URL to the oEmbed provider.
2240 * @param boolean $regex Optional. Whether the `$format` parameter is in a RegEx format. Default false.
2242 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
2243 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2245 if ( did_action( 'plugins_loaded' ) ) {
2246 $oembed = _wp_oembed_get_object();
2247 $oembed->providers[$format] = array( $provider, $regex );
2249 WP_oEmbed::_add_provider_early( $format, $provider, $regex );
2254 * Removes an oEmbed provider.
2260 * @param string $format The URL format for the oEmbed provider to remove.
2261 * @return bool Was the provider removed successfully?
2263 function wp_oembed_remove_provider( $format ) {
2264 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2266 if ( did_action( 'plugins_loaded' ) ) {
2267 $oembed = _wp_oembed_get_object();
2269 if ( isset( $oembed->providers[ $format ] ) ) {
2270 unset( $oembed->providers[ $format ] );
2274 WP_oEmbed::_remove_provider_early( $format );
2281 * Determines if default embed handlers should be loaded.
2283 * Checks to make sure that the embeds library hasn't already been loaded. If
2284 * it hasn't, then it will load the embeds library.
2288 * @see wp_embed_register_handler()
2290 function wp_maybe_load_embeds() {
2292 * Filter whether to load the default embed handlers.
2294 * Returning a falsey value will prevent loading the default embed handlers.
2298 * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
2300 if ( ! apply_filters( 'load_default_embeds', true ) ) {
2304 wp_embed_register_handler( 'youtube_embed_url', '#https?://(www.)?youtube\.com/embed/([^/]+)#i', 'wp_embed_handler_youtube' );
2306 wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
2309 * Filter the audio embed handler callback.
2313 * @param callback $handler Audio embed handler callback function.
2315 wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
2318 * Filter the video embed handler callback.
2322 * @param callback $handler Video embed handler callback function.
2324 wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
2328 * The Google Video embed handler callback.
2330 * Google Video does not support oEmbed.
2332 * @see WP_Embed::register_handler()
2333 * @see WP_Embed::shortcode()
2335 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2336 * @param array $attr Embed attributes.
2337 * @param string $url The original URL that was matched by the regex.
2338 * @param array $rawattr The original unmodified attributes.
2339 * @return string The embed HTML.
2341 function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
2342 // If the user supplied a fixed width AND height, use it
2343 if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
2344 $width = (int) $rawattr['width'];
2345 $height = (int) $rawattr['height'];
2347 list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
2351 * Filter the Google Video embed output.
2355 * @param string $html Google Video HTML embed markup.
2356 * @param array $matches The RegEx matches from the provided regex.
2357 * @param array $attr An array of embed attributes.
2358 * @param string $url The original URL that was matched by the regex.
2359 * @param array $rawattr The original unmodified attributes.
2361 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 );
2365 * YouTube iframe embed handler callback.
2367 * Catches YouTube iframe embed URLs that are not parsable by oEmbed but can be translated into a URL that is.
2371 * @param array $matches The RegEx matches from the provided regex when calling
2372 * wp_embed_register_handler().
2373 * @param array $attr Embed attributes.
2374 * @param string $url The original URL that was matched by the regex.
2375 * @param array $rawattr The original unmodified attributes.
2376 * @return string The embed HTML.
2378 function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
2380 $embed = $wp_embed->autoembed( "https://youtube.com/watch?v={$matches[2]}" );
2383 * Filter the YoutTube embed output.
2387 * @see wp_embed_handler_youtube()
2389 * @param string $embed YouTube embed output.
2390 * @param array $attr An array of embed attributes.
2391 * @param string $url The original URL that was matched by the regex.
2392 * @param array $rawattr The original unmodified attributes.
2394 return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
2398 * Audio embed handler callback.
2402 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2403 * @param array $attr Embed attributes.
2404 * @param string $url The original URL that was matched by the regex.
2405 * @param array $rawattr The original unmodified attributes.
2406 * @return string The embed HTML.
2408 function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
2409 $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
2412 * Filter the audio embed output.
2416 * @param string $audio Audio embed output.
2417 * @param array $attr An array of embed attributes.
2418 * @param string $url The original URL that was matched by the regex.
2419 * @param array $rawattr The original unmodified attributes.
2421 return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
2425 * Video embed handler callback.
2429 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2430 * @param array $attr Embed attributes.
2431 * @param string $url The original URL that was matched by the regex.
2432 * @param array $rawattr The original unmodified attributes.
2433 * @return string The embed HTML.
2435 function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
2437 if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
2438 $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
2439 $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
2441 $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
2444 * Filter the video embed output.
2448 * @param string $video Video embed output.
2449 * @param array $attr An array of embed attributes.
2450 * @param string $url The original URL that was matched by the regex.
2451 * @param array $rawattr The original unmodified attributes.
2453 return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
2457 * Converts a shorthand byte value to an integer byte value.
2461 * @param string $size A shorthand byte value.
2462 * @return int An integer byte value.
2464 function wp_convert_hr_to_bytes( $size ) {
2465 $size = strtolower( $size );
2466 $bytes = (int) $size;
2467 if ( strpos( $size, 'k' ) !== false )
2468 $bytes = intval( $size ) * 1024;
2469 elseif ( strpos( $size, 'm' ) !== false )
2470 $bytes = intval($size) * 1024 * 1024;
2471 elseif ( strpos( $size, 'g' ) !== false )
2472 $bytes = intval( $size ) * 1024 * 1024 * 1024;
2477 * Determines the maximum upload size allowed in php.ini.
2481 * @return int Allowed upload size.
2483 function wp_max_upload_size() {
2484 $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2485 $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2488 * Filter the maximum upload size allowed in php.ini.
2492 * @param int $size Max upload size limit in bytes.
2493 * @param int $u_bytes Maximum upload filesize in bytes.
2494 * @param int $p_bytes Maximum size of POST data in bytes.
2496 return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2500 * Returns a WP_Image_Editor instance and loads file into it.
2504 * @param string $path Path to the file to load.
2505 * @param array $args Optional. Additional arguments for retrieving the image editor.
2506 * Default empty array.
2507 * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
2510 function wp_get_image_editor( $path, $args = array() ) {
2511 $args['path'] = $path;
2513 if ( ! isset( $args['mime_type'] ) ) {
2514 $file_info = wp_check_filetype( $args['path'] );
2516 // If $file_info['type'] is false, then we let the editor attempt to
2517 // figure out the file type, rather than forcing a failure based on extension.
2518 if ( isset( $file_info ) && $file_info['type'] )
2519 $args['mime_type'] = $file_info['type'];
2522 $implementation = _wp_image_editor_choose( $args );
2524 if ( $implementation ) {
2525 $editor = new $implementation( $path );
2526 $loaded = $editor->load();
2528 if ( is_wp_error( $loaded ) )
2534 return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
2538 * Tests whether there is an editor that supports a given mime type or methods.
2542 * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
2543 * Default empty array.
2544 * @return bool True if an eligible editor is found; false otherwise.
2546 function wp_image_editor_supports( $args = array() ) {
2547 return (bool) _wp_image_editor_choose( $args );
2551 * Tests which editors are capable of supporting the request.
2556 * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
2557 * @return string|bool Class name for the first editor that claims to support the request. False if no
2558 * editor claims to support the request.
2560 function _wp_image_editor_choose( $args = array() ) {
2561 require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
2562 require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
2563 require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
2566 * Filter the list of image editing library classes.
2570 * @param array $image_editors List of available image editors. Defaults are
2571 * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
2573 $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
2575 foreach ( $implementations as $implementation ) {
2576 if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
2579 if ( isset( $args['mime_type'] ) &&
2581 array( $implementation, 'supports_mime_type' ),
2582 $args['mime_type'] ) ) {
2586 if ( isset( $args['methods'] ) &&
2587 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
2591 return $implementation;
2598 * Prints default plupload arguments.
2602 function wp_plupload_default_settings() {
2605 $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
2606 if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
2609 $max_upload_size = wp_max_upload_size();
2612 'runtimes' => 'html5,flash,silverlight,html4',
2613 'file_data_name' => 'async-upload', // key passed to $_FILE.
2614 'url' => admin_url( 'async-upload.php', 'relative' ),
2615 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
2616 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
2618 'max_file_size' => $max_upload_size . 'b',
2622 // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
2623 // when enabled. See #29602.
2624 if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
2625 strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
2627 $defaults['multi_selection'] = false;
2631 * Filter the Plupload default settings.
2635 * @param array $defaults Default Plupload settings array.
2637 $defaults = apply_filters( 'plupload_default_settings', $defaults );
2640 'action' => 'upload-attachment',
2644 * Filter the Plupload default parameters.
2648 * @param array $params Default Plupload parameters array.
2650 $params = apply_filters( 'plupload_default_params', $params );
2651 $params['_wpnonce'] = wp_create_nonce( 'media-form' );
2652 $defaults['multipart_params'] = $params;
2655 'defaults' => $defaults,
2657 'mobile' => wp_is_mobile(),
2658 'supported' => _device_can_upload(),
2660 'limitExceeded' => is_multisite() && ! is_upload_space_available()
2663 $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
2666 $script = "$data\n$script";
2668 $wp_scripts->add_data( 'wp-plupload', 'data', $script );
2672 * Prepares an attachment post object for JS, where it is expected
2673 * to be JSON-encoded and fit into an Attachment model.
2677 * @param mixed $attachment Attachment ID or object.
2678 * @return array Array of attachment details.
2680 function wp_prepare_attachment_for_js( $attachment ) {
2681 if ( ! $attachment = get_post( $attachment ) )
2684 if ( 'attachment' != $attachment->post_type )
2687 $meta = wp_get_attachment_metadata( $attachment->ID );
2688 if ( false !== strpos( $attachment->post_mime_type, '/' ) )
2689 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
2691 list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
2693 $attachment_url = wp_get_attachment_url( $attachment->ID );
2696 'id' => $attachment->ID,
2697 'title' => $attachment->post_title,
2698 'filename' => wp_basename( $attachment->guid ),
2699 'url' => $attachment_url,
2700 'link' => get_attachment_link( $attachment->ID ),
2701 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
2702 'author' => $attachment->post_author,
2703 'description' => $attachment->post_content,
2704 'caption' => $attachment->post_excerpt,
2705 'name' => $attachment->post_name,
2706 'status' => $attachment->post_status,
2707 'uploadedTo' => $attachment->post_parent,
2708 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
2709 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
2710 'menuOrder' => $attachment->menu_order,
2711 'mime' => $attachment->post_mime_type,
2713 'subtype' => $subtype,
2714 'icon' => wp_mime_type_icon( $attachment->ID ),
2715 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
2721 'editLink' => false,
2725 $author = new WP_User( $attachment->post_author );
2726 $response['authorName'] = $author->display_name;
2728 if ( $attachment->post_parent ) {
2729 $post_parent = get_post( $attachment->post_parent );
2731 $post_parent = false;
2734 if ( $post_parent ) {
2735 $parent_type = get_post_type_object( $post_parent->post_type );
2736 if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
2737 $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
2739 $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
2742 $attached_file = get_attached_file( $attachment->ID );
2743 if ( file_exists( $attached_file ) ) {
2744 $bytes = filesize( $attached_file );
2745 $response['filesizeInBytes'] = $bytes;
2746 $response['filesizeHumanReadable'] = size_format( $bytes );
2749 if ( current_user_can( 'edit_post', $attachment->ID ) ) {
2750 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
2751 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
2752 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
2755 if ( current_user_can( 'delete_post', $attachment->ID ) )
2756 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
2758 if ( $meta && 'image' === $type ) {
2761 /** This filter is documented in wp-admin/includes/media.php */
2762 $possible_sizes = apply_filters( 'image_size_names_choose', array(
2763 'thumbnail' => __('Thumbnail'),
2764 'medium' => __('Medium'),
2765 'large' => __('Large'),
2766 'full' => __('Full Size'),
2768 unset( $possible_sizes['full'] );
2770 // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
2771 // First: run the image_downsize filter. If it returns something, we can use its data.
2772 // If the filter does not return something, then image_downsize() is just an expensive
2773 // way to check the image metadata, which we do second.
2774 foreach ( $possible_sizes as $size => $label ) {
2776 /** This filter is documented in wp-includes/media.php */
2777 if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
2778 if ( ! $downsize[3] )
2780 $sizes[ $size ] = array(
2781 'height' => $downsize[2],
2782 'width' => $downsize[1],
2783 'url' => $downsize[0],
2784 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
2786 } elseif ( isset( $meta['sizes'][ $size ] ) ) {
2787 if ( ! isset( $base_url ) )
2788 $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
2790 // Nothing from the filter, so consult image metadata if we have it.
2791 $size_meta = $meta['sizes'][ $size ];
2793 // We have the actual image size, but might need to further constrain it if content_width is narrower.
2794 // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
2795 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
2797 $sizes[ $size ] = array(
2798 'height' => $height,
2800 'url' => $base_url . $size_meta['file'],
2801 'orientation' => $height > $width ? 'portrait' : 'landscape',
2806 $sizes['full'] = array( 'url' => $attachment_url );
2808 if ( isset( $meta['height'], $meta['width'] ) ) {
2809 $sizes['full']['height'] = $meta['height'];
2810 $sizes['full']['width'] = $meta['width'];
2811 $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
2814 $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
2815 } elseif ( $meta && 'video' === $type ) {
2816 if ( isset( $meta['width'] ) )
2817 $response['width'] = (int) $meta['width'];
2818 if ( isset( $meta['height'] ) )
2819 $response['height'] = (int) $meta['height'];
2822 if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
2823 if ( isset( $meta['length_formatted'] ) )
2824 $response['fileLength'] = $meta['length_formatted'];
2826 $response['meta'] = array();
2827 foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
2828 $response['meta'][ $key ] = false;
2830 if ( ! empty( $meta[ $key ] ) ) {
2831 $response['meta'][ $key ] = $meta[ $key ];
2835 $id = get_post_thumbnail_id( $attachment->ID );
2836 if ( ! empty( $id ) ) {
2837 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
2838 $response['image'] = compact( 'src', 'width', 'height' );
2839 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
2840 $response['thumb'] = compact( 'src', 'width', 'height' );
2842 $src = wp_mime_type_icon( $attachment->ID );
2845 $response['image'] = compact( 'src', 'width', 'height' );
2846 $response['thumb'] = compact( 'src', 'width', 'height' );
2850 if ( function_exists('get_compat_media_markup') )
2851 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
2854 * Filter the attachment data prepared for JavaScript.
2858 * @param array $response Array of prepared attachment data.
2859 * @param int|object $attachment Attachment ID or object.
2860 * @param array $meta Array of attachment meta data.
2862 return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
2866 * Enqueues all scripts, styles, settings, and templates necessary to use
2867 * all media JS APIs.
2871 * @param array $args {
2872 * Arguments for enqueuing media scripts.
2874 * @type int|WP_Post A post object or ID.
2876 * @return array List of media view settings.
2878 function wp_enqueue_media( $args = array() ) {
2880 // Enqueue me just once per page, please.
2881 if ( did_action( 'wp_enqueue_media' ) )
2884 global $content_width, $wpdb, $wp_locale;
2889 $args = wp_parse_args( $args, $defaults );
2891 // We're going to pass the old thickbox media tabs to `media_upload_tabs`
2892 // to ensure plugins will work. We will then unset those tabs.
2894 // handler action suffix => tab label
2901 /** This filter is documented in wp-admin/includes/media.php */
2902 $tabs = apply_filters( 'media_upload_tabs', $tabs );
2903 unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
2906 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
2907 'align' => get_option( 'image_default_align' ), // empty default
2908 'size' => get_option( 'image_default_size' ), // empty default
2911 $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
2912 $mimes = get_allowed_mime_types();
2913 $ext_mimes = array();
2914 foreach ( $exts as $ext ) {
2915 foreach ( $mimes as $ext_preg => $mime_match ) {
2916 if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
2917 $ext_mimes[ $ext ] = $mime_match;
2923 $has_audio = $wpdb->get_var( "
2926 WHERE post_type = 'attachment'
2927 AND post_mime_type LIKE 'audio%'
2930 $has_video = $wpdb->get_var( "
2933 WHERE post_type = 'attachment'
2934 AND post_mime_type LIKE 'video%'
2937 $months = $wpdb->get_results( $wpdb->prepare( "
2938 SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
2940 WHERE post_type = %s
2941 ORDER BY post_date DESC
2942 ", 'attachment' ) );
2943 foreach ( $months as $month_year ) {
2944 $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
2949 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
2950 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
2951 /** This filter is documented in wp-admin/includes/media.php */
2952 'captions' => ! apply_filters( 'disable_captions', '' ),
2954 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
2959 'defaultProps' => $props,
2960 'attachmentCounts' => array(
2961 'audio' => ( $has_audio ) ? 1 : 0,
2962 'video' => ( $has_video ) ? 1 : 0
2964 'embedExts' => $exts,
2965 'embedMimes' => $ext_mimes,
2966 'contentWidth' => $content_width,
2967 'months' => $months,
2968 'mediaTrash' => MEDIA_TRASH ? 1 : 0
2972 if ( isset( $args['post'] ) ) {
2973 $post = get_post( $args['post'] );
2974 $settings['post'] = array(
2976 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
2979 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
2980 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
2981 if ( wp_attachment_is( 'audio', $post ) ) {
2982 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
2983 } elseif ( wp_attachment_is( 'video', $post ) ) {
2984 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
2988 if ( $thumbnail_support ) {
2989 $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
2990 $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
2994 $hier = $post && is_post_type_hierarchical( $post->post_type );
2998 'url' => __( 'URL' ),
2999 'addMedia' => __( 'Add Media' ),
3000 'search' => __( 'Search' ),
3001 'select' => __( 'Select' ),
3002 'cancel' => __( 'Cancel' ),
3003 'update' => __( 'Update' ),
3004 'replace' => __( 'Replace' ),
3005 'remove' => __( 'Remove' ),
3006 'back' => __( 'Back' ),
3007 /* translators: This is a would-be plural string used in the media manager.
3008 If there is not a word you can use in your language to avoid issues with the
3009 lack of plural support here, turn it into "selected: %d" then translate it.
3011 'selected' => __( '%d selected' ),
3012 'dragInfo' => __( 'Drag and drop to reorder media files.' ),
3015 'uploadFilesTitle' => __( 'Upload Files' ),
3016 'uploadImagesTitle' => __( 'Upload Images' ),
3019 'mediaLibraryTitle' => __( 'Media Library' ),
3020 'insertMediaTitle' => __( 'Insert Media' ),
3021 'createNewGallery' => __( 'Create a new gallery' ),
3022 'createNewPlaylist' => __( 'Create a new playlist' ),
3023 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
3024 'returnToLibrary' => __( '← Return to library' ),
3025 'allMediaItems' => __( 'All media items' ),
3026 'allDates' => __( 'All dates' ),
3027 'noItemsFound' => __( 'No items found.' ),
3028 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
3029 'unattached' => __( 'Unattached' ),
3030 'trash' => _x( 'Trash', 'noun' ),
3031 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
3032 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
3033 'warnBulkDelete' => __( "You are about to permanently delete these items.\n 'Cancel' to stop, 'OK' to delete." ),
3034 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
3035 'bulkSelect' => __( 'Bulk Select' ),
3036 'cancelSelection' => __( 'Cancel Selection' ),
3037 'trashSelected' => __( 'Trash Selected' ),
3038 'untrashSelected' => __( 'Untrash Selected' ),
3039 'deleteSelected' => __( 'Delete Selected' ),
3040 'deletePermanently' => __( 'Delete Permanently' ),
3041 'apply' => __( 'Apply' ),
3042 'filterByDate' => __( 'Filter by date' ),
3043 'filterByType' => __( 'Filter by type' ),
3044 'searchMediaLabel' => __( 'Search Media' ),
3045 'noMedia' => __( 'No media attachments found.' ),
3048 'attachmentDetails' => __( 'Attachment Details' ),
3051 'insertFromUrlTitle' => __( 'Insert from URL' ),
3054 'setFeaturedImageTitle' => __( 'Set Featured Image' ),
3055 'setFeaturedImage' => __( 'Set featured image' ),
3058 'createGalleryTitle' => __( 'Create Gallery' ),
3059 'editGalleryTitle' => __( 'Edit Gallery' ),
3060 'cancelGalleryTitle' => __( '← Cancel Gallery' ),
3061 'insertGallery' => __( 'Insert gallery' ),
3062 'updateGallery' => __( 'Update gallery' ),
3063 'addToGallery' => __( 'Add to gallery' ),
3064 'addToGalleryTitle' => __( 'Add to Gallery' ),
3065 'reverseOrder' => __( 'Reverse order' ),
3068 'imageDetailsTitle' => __( 'Image Details' ),
3069 'imageReplaceTitle' => __( 'Replace Image' ),
3070 'imageDetailsCancel' => __( 'Cancel Edit' ),
3071 'editImage' => __( 'Edit Image' ),
3074 'chooseImage' => __( 'Choose Image' ),
3075 'selectAndCrop' => __( 'Select and Crop' ),
3076 'skipCropping' => __( 'Skip Cropping' ),
3077 'cropImage' => __( 'Crop Image' ),
3078 'cropYourImage' => __( 'Crop your image' ),
3079 'cropping' => __( 'Cropping…' ),
3080 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
3081 'cropError' => __( 'There has been an error cropping your image.' ),
3084 'audioDetailsTitle' => __( 'Audio Details' ),
3085 'audioReplaceTitle' => __( 'Replace Audio' ),
3086 'audioAddSourceTitle' => __( 'Add Audio Source' ),
3087 'audioDetailsCancel' => __( 'Cancel Edit' ),
3090 'videoDetailsTitle' => __( 'Video Details' ),
3091 'videoReplaceTitle' => __( 'Replace Video' ),
3092 'videoAddSourceTitle' => __( 'Add Video Source' ),
3093 'videoDetailsCancel' => __( 'Cancel Edit' ),
3094 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
3095 'videoAddTrackTitle' => __( 'Add Subtitles' ),
3098 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
3099 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
3100 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
3101 'cancelPlaylistTitle' => __( '← Cancel Audio Playlist' ),
3102 'insertPlaylist' => __( 'Insert audio playlist' ),
3103 'updatePlaylist' => __( 'Update audio playlist' ),
3104 'addToPlaylist' => __( 'Add to audio playlist' ),
3105 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
3108 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
3109 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
3110 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
3111 'cancelVideoPlaylistTitle' => __( '← Cancel Video Playlist' ),
3112 'insertVideoPlaylist' => __( 'Insert video playlist' ),
3113 'updateVideoPlaylist' => __( 'Update video playlist' ),
3114 'addToVideoPlaylist' => __( 'Add to video playlist' ),
3115 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
3119 * Filter the media view settings.
3123 * @param array $settings List of media view settings.
3124 * @param WP_Post $post Post object.
3126 $settings = apply_filters( 'media_view_settings', $settings, $post );
3129 * Filter the media view strings.
3133 * @param array $strings List of media view strings.
3134 * @param WP_Post $post Post object.
3136 $strings = apply_filters( 'media_view_strings', $strings, $post );
3138 $strings['settings'] = $settings;
3140 // Ensure we enqueue media-editor first, that way media-views is
3141 // registered internally before we try to localize it. see #24724.
3142 wp_enqueue_script( 'media-editor' );
3143 wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
3145 wp_enqueue_script( 'media-audiovideo' );
3146 wp_enqueue_style( 'media-views' );
3148 wp_enqueue_script( 'mce-view' );
3149 wp_enqueue_script( 'image-edit' );
3151 wp_enqueue_style( 'imgareaselect' );
3152 wp_plupload_default_settings();
3154 require_once ABSPATH . WPINC . '/media-template.php';
3155 add_action( 'admin_footer', 'wp_print_media_templates' );
3156 add_action( 'wp_footer', 'wp_print_media_templates' );
3157 add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
3160 * Fires at the conclusion of wp_enqueue_media().
3164 do_action( 'wp_enqueue_media' );
3168 * Retrieves media attached to the passed post.
3172 * @param string $type Mime type.
3173 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3174 * @return array Found attachments.
3176 function get_attached_media( $type, $post = 0 ) {
3177 if ( ! $post = get_post( $post ) )
3181 'post_parent' => $post->ID,
3182 'post_type' => 'attachment',
3183 'post_mime_type' => $type,
3184 'posts_per_page' => -1,
3185 'orderby' => 'menu_order',
3190 * Filter arguments used to retrieve media attached to the given post.
3194 * @param array $args Post query arguments.
3195 * @param string $type Mime type of the desired media.
3196 * @param mixed $post Post ID or object.
3198 $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
3200 $children = get_children( $args );
3203 * Filter the list of media attached to the given post.
3207 * @param array $children Associative array of media attached to the given post.
3208 * @param string $type Mime type of the media desired.
3209 * @param mixed $post Post ID or object.
3211 return (array) apply_filters( 'get_attached_media', $children, $type, $post );
3215 * Check the content blob for an audio, video, object, embed, or iframe tags.
3219 * @param string $content A string which might contain media data.
3220 * @param array $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
3221 * @return array A list of found HTML media embeds.
3223 function get_media_embedded_in_content( $content, $types = null ) {
3227 * Filter the embedded media types that are allowed to be returned from the content blob.
3231 * @param array $allowed_media_types An array of allowed media types. Default media types are
3232 * 'audio', 'video', 'object', 'embed', and 'iframe'.
3234 $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
3236 if ( ! empty( $types ) ) {
3237 if ( ! is_array( $types ) ) {
3238 $types = array( $types );
3241 $allowed_media_types = array_intersect( $allowed_media_types, $types );
3244 $tags = implode( '|', $allowed_media_types );
3246 if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
3247 foreach ( $matches[0] as $match ) {
3256 * Retrieves galleries from the passed post's content.
3260 * @param int|WP_Post $post Post ID or object.
3261 * @param bool $html Optional. Whether to return HTML or data in the array. Default true.
3262 * @return array A list of arrays, each containing gallery data and srcs parsed
3263 * from the expanded shortcode.
3265 function get_post_galleries( $post, $html = true ) {
3266 if ( ! $post = get_post( $post ) )
3269 if ( ! has_shortcode( $post->post_content, 'gallery' ) )
3272 $galleries = array();
3273 if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
3274 foreach ( $matches as $shortcode ) {
3275 if ( 'gallery' === $shortcode[2] ) {
3278 $gallery = do_shortcode_tag( $shortcode );
3280 $galleries[] = $gallery;
3282 preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
3283 if ( ! empty( $src ) ) {
3284 foreach ( $src as $s )
3288 $data = shortcode_parse_atts( $shortcode[3] );
3289 $data['src'] = array_values( array_unique( $srcs ) );
3290 $galleries[] = $data;
3297 * Filter the list of all found galleries in the given post.
3301 * @param array $galleries Associative array of all found post galleries.
3302 * @param WP_Post $post Post object.
3304 return apply_filters( 'get_post_galleries', $galleries, $post );
3308 * Check a specified post's content for gallery and, if present, return the first
3312 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3313 * @param bool $html Optional. Whether to return HTML or data. Default is true.
3314 * @return string|array Gallery data and srcs parsed from the expanded shortcode.
3316 function get_post_gallery( $post = 0, $html = true ) {
3317 $galleries = get_post_galleries( $post, $html );
3318 $gallery = reset( $galleries );
3321 * Filter the first-found post gallery.
3325 * @param array $gallery The first-found post gallery.
3326 * @param int|WP_Post $post Post ID or object.
3327 * @param array $galleries Associative array of all found post galleries.
3329 return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
3333 * Retrieve the image srcs from galleries from a post's content, if present
3337 * @see get_post_galleries()
3339 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3340 * @return array A list of lists, each containing image srcs parsed.
3341 * from an expanded shortcode
3343 function get_post_galleries_images( $post = 0 ) {
3344 $galleries = get_post_galleries( $post, false );
3345 return wp_list_pluck( $galleries, 'src' );
3349 * Checks a post's content for galleries and return the image srcs for the first found gallery
3353 * @see get_post_gallery()
3355 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3356 * @return array A list of a gallery's image srcs in order.
3358 function get_post_gallery_images( $post = 0 ) {
3359 $gallery = get_post_gallery( $post, false );
3360 return empty( $gallery['src'] ) ? array() : $gallery['src'];
3364 * Maybe attempts to generate attachment metadata, if missing.
3368 * @param WP_Post $attachment Attachment object.
3370 function wp_maybe_generate_attachment_metadata( $attachment ) {
3371 if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
3375 $file = get_attached_file( $attachment_id );
3376 $meta = wp_get_attachment_metadata( $attachment_id );
3377 if ( empty( $meta ) && file_exists( $file ) ) {
3378 $_meta = get_post_meta( $attachment_id );
3379 $regeneration_lock = 'wp_generating_att_' . $attachment_id;
3380 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
3381 set_transient( $regeneration_lock, $file );
3382 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
3383 delete_transient( $regeneration_lock );
3389 * Tries to convert an attachment URL into a post ID.
3393 * @global wpdb $wpdb WordPress database abstraction object.
3395 * @param string $url The URL to resolve.
3396 * @return int The found post ID, or 0 on failure.
3398 function attachment_url_to_postid( $url ) {
3401 $dir = wp_upload_dir();
3404 if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
3405 $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
3408 $sql = $wpdb->prepare(
3409 "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
3412 $post_id = $wpdb->get_var( $sql );
3415 * Filter an attachment id found by URL.
3419 * @param int|null $post_id The post_id (if any) found by the function.
3420 * @param string $url The URL being looked up.
3422 $post_id = apply_filters( 'attachment_url_to_postid', $post_id, $url );
3424 return (int) $post_id;
3428 * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
3432 * @global $wp_version
3434 * @return array The relevant CSS file URLs.
3436 function wpview_media_sandbox_styles() {
3437 $version = 'ver=' . $GLOBALS['wp_version'];
3438 $mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
3439 $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
3441 return array( $mediaelement, $wpmediaelement );