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' ) {
62 // We're inserting a large size image into the editor. If it's a really
63 // big image we'll scale it down to fit reasonably within the editor
64 // itself, and within the theme's content width if it's known. The user
65 // can resize it in the editor if they wish.
66 $max_width = intval(get_option('large_size_w'));
67 $max_height = intval(get_option('large_size_h'));
68 if ( intval($content_width) > 0 )
69 $max_width = min( intval($content_width), $max_width );
70 } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
71 $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
72 $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
73 if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
74 $max_width = min( intval($content_width), $max_width );
76 // $size == 'full' has no constraint
79 $max_height = $height;
83 * Filter the maximum image size dimensions for the editor.
87 * @param array $max_image_size An array with the width as the first element,
88 * and the height as the second element.
89 * @param string|array $size Size of what the result image should be.
90 * @param string $context The context the image is being resized for.
91 * Possible values are 'display' (like in a theme)
92 * or 'edit' (like inserting into an editor).
94 list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
96 return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
100 * Retrieve width and height attributes using given width and height values.
102 * Both attributes are required in the sense that both parameters must have a
103 * value, but are optional in that if you set them to false or null, then they
104 * will not be added to the returned string.
106 * You can set the value using a string, but it will only take numeric values.
107 * If you wish to put 'px' after the numbers, then it will be stripped out of
112 * @param int|string $width Optional. Width attribute value.
113 * @param int|string $height Optional. Height attribute value.
114 * @return string HTML attributes for width and, or height.
116 function image_hwstring($width, $height) {
119 $out .= 'width="'.intval($width).'" ';
121 $out .= 'height="'.intval($height).'" ';
126 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
128 * Array with image url, width, height, and whether is intermediate size, in
129 * that order is returned on success is returned. $is_intermediate is true if
130 * $url is a resized image, false if it is the original.
132 * The URL might be the original image, or it might be a resized version. This
133 * function won't create a new resized copy, it will just return an already
134 * resized one if it exists.
136 * A plugin may use the 'image_downsize' filter to hook into and offer image
137 * resizing services for images. The hook must return an array with the same
138 * elements that are returned in the function. The first element being the URL
139 * to the new image that was resized.
143 * @param int $id Attachment ID for image.
144 * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
145 * @return bool|array False on failure, array on success.
147 function image_downsize($id, $size = 'medium') {
149 if ( !wp_attachment_is_image($id) )
153 * Filter whether to preempt the output of image_downsize().
155 * Passing a truthy value to the filter will effectively short-circuit
156 * down-sizing the image, returning that value as output instead.
160 * @param bool $downsize Whether to short-circuit the image downsize. Default false.
161 * @param int $id Attachment ID for image.
162 * @param array|string $size Size of image, either array or string. Default 'medium'.
164 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
168 $img_url = wp_get_attachment_url($id);
169 $meta = wp_get_attachment_metadata($id);
170 $width = $height = 0;
171 $is_intermediate = false;
172 $img_url_basename = wp_basename($img_url);
174 // try for a new style intermediate size
175 if ( $intermediate = image_get_intermediate_size($id, $size) ) {
176 $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
177 $width = $intermediate['width'];
178 $height = $intermediate['height'];
179 $is_intermediate = true;
181 elseif ( $size == 'thumbnail' ) {
182 // fall back to the old thumbnail
183 if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
184 $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
187 $is_intermediate = true;
190 if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
191 // any other type: use the real image
192 $width = $meta['width'];
193 $height = $meta['height'];
197 // we have the actual image size, but might need to further constrain it if content_width is narrower
198 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
200 return array( $img_url, $width, $height, $is_intermediate );
207 * Register a new image size.
209 * Cropping behavior for the image size is dependent on the value of $crop:
210 * 1. If false (default), images will be scaled, not cropped.
211 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
212 * - x_crop_position accepts 'left' 'center', or 'right'.
213 * - y_crop_position accepts 'top', 'center', or 'bottom'.
214 * Images will be cropped to the specified dimensions within the defined crop area.
215 * 3. If true, images will be cropped to the specified dimensions using center positions.
219 * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
221 * @param string $name Image size identifier.
222 * @param int $width Image width in pixels.
223 * @param int $height Image height in pixels.
224 * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
225 * An array can specify positioning of the crop area. Default false.
227 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
228 global $_wp_additional_image_sizes;
230 $_wp_additional_image_sizes[ $name ] = array(
231 'width' => absint( $width ),
232 'height' => absint( $height ),
238 * Check if an image size exists.
242 * @param string $name The image size to check.
243 * @return bool True if the image size exists, false if not.
245 function has_image_size( $name ) {
246 global $_wp_additional_image_sizes;
248 return isset( $_wp_additional_image_sizes[ $name ] );
252 * Remove a new image size.
256 * @param string $name The image size to remove.
257 * @return bool True if the image size was successfully removed, false on failure.
259 function remove_image_size( $name ) {
260 global $_wp_additional_image_sizes;
262 if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
263 unset( $_wp_additional_image_sizes[ $name ] );
271 * Registers an image size for the post thumbnail.
275 * @see add_image_size() for details on cropping behavior.
277 * @param int $width Image width in pixels.
278 * @param int $height Image height in pixels.
279 * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
280 * An array can specify positioning of the crop area. Default false.
282 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
283 add_image_size( 'post-thumbnail', $width, $height, $crop );
287 * An <img src /> tag for an image attachment, scaling it down if requested.
289 * The filter 'get_image_tag_class' allows for changing the class name for the
290 * image without having to use regular expressions on the HTML content. The
291 * parameters are: what WordPress will use for the class, the Attachment ID,
292 * image align value, and the size the image should be.
294 * The second filter 'get_image_tag' has the HTML content, which can then be
295 * further manipulated by a plugin to change all attribute values and even HTML
300 * @param int $id Attachment ID.
301 * @param string $alt Image Description for the alt attribute.
302 * @param string $title Image Description for the title attribute.
303 * @param string $align Part of the class name for aligning the image.
304 * @param string $size Optional. Default is 'medium'.
305 * @return string HTML IMG element for given image attachment
307 function get_image_tag($id, $alt, $title, $align, $size='medium') {
309 list( $img_src, $width, $height ) = image_downsize($id, $size);
310 $hwstring = image_hwstring($width, $height);
312 $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
314 $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
317 * Filter the value of the attachment's image tag class attribute.
321 * @param string $class CSS class name or space-separated list of classes.
322 * @param int $id Attachment ID.
323 * @param string $align Part of the class name for aligning the image.
324 * @param string $size Optional. Default is 'medium'.
326 $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
328 $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
331 * Filter the HTML content for the image tag.
335 * @param string $html HTML content for the image.
336 * @param int $id Attachment ID.
337 * @param string $alt Alternate text.
338 * @param string $title Attachment title.
339 * @param string $align Part of the class name for aligning the image.
340 * @param string $size Optional. Default is 'medium'.
342 $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
348 * Calculates the new dimensions for a downsampled image.
350 * If either width or height are empty, no constraint is applied on
355 * @param int $current_width Current width of the image.
356 * @param int $current_height Current height of the image.
357 * @param int $max_width Optional. Maximum wanted width.
358 * @param int $max_height Optional. Maximum wanted height.
359 * @return array First item is the width, the second item is the height.
361 function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
362 if ( !$max_width and !$max_height )
363 return array( $current_width, $current_height );
365 $width_ratio = $height_ratio = 1.0;
366 $did_width = $did_height = false;
368 if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
369 $width_ratio = $max_width / $current_width;
373 if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
374 $height_ratio = $max_height / $current_height;
378 // Calculate the larger/smaller ratios
379 $smaller_ratio = min( $width_ratio, $height_ratio );
380 $larger_ratio = max( $width_ratio, $height_ratio );
382 if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
383 // The larger ratio is too big. It would result in an overflow.
384 $ratio = $smaller_ratio;
386 // The larger ratio fits, and is likely to be a more "snug" fit.
387 $ratio = $larger_ratio;
390 // Very small dimensions may result in 0, 1 should be the minimum.
391 $w = max ( 1, (int) round( $current_width * $ratio ) );
392 $h = max ( 1, (int) round( $current_height * $ratio ) );
394 // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
395 // 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.
396 // Thus we look for dimensions that are one pixel shy of the max value and bump them up
398 // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
399 if ( $did_width && $w == $max_width - 1 ) {
400 $w = $max_width; // Round it up
403 // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
404 if ( $did_height && $h == $max_height - 1 ) {
405 $h = $max_height; // Round it up
408 return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
412 * Retrieve calculated resize dimensions for use in WP_Image_Editor.
414 * Calculates dimensions and coordinates for a resized image that fits
415 * within a specified width and height.
417 * Cropping behavior is dependent on the value of $crop:
418 * 1. If false (default), images will not be cropped.
419 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
420 * - x_crop_position accepts 'left' 'center', or 'right'.
421 * - y_crop_position accepts 'top', 'center', or 'bottom'.
422 * Images will be cropped to the specified dimensions within the defined crop area.
423 * 3. If true, images will be cropped to the specified dimensions using center positions.
427 * @param int $orig_w Original width in pixels.
428 * @param int $orig_h Original height in pixels.
429 * @param int $dest_w New width in pixels.
430 * @param int $dest_h New height in pixels.
431 * @param bool|array $crop Optional. Whether to crop image to specified height and width or resize.
432 * An array can specify positioning of the crop area. Default false.
433 * @return bool|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
435 function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
437 if ($orig_w <= 0 || $orig_h <= 0)
439 // at least one of dest_w or dest_h must be specific
440 if ($dest_w <= 0 && $dest_h <= 0)
444 * Filter whether to preempt calculating the image resize dimensions.
446 * Passing a non-null value to the filter will effectively short-circuit
447 * image_resize_dimensions(), returning that value instead.
451 * @param null|mixed $null Whether to preempt output of the resize dimensions.
452 * @param int $orig_w Original width in pixels.
453 * @param int $orig_h Original height in pixels.
454 * @param int $dest_w New width in pixels.
455 * @param int $dest_h New height in pixels.
456 * @param bool|array $crop Whether to crop image to specified height and width or resize.
457 * An array can specify positioning of the crop area. Default false.
459 $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
460 if ( null !== $output )
464 // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
465 $aspect_ratio = $orig_w / $orig_h;
466 $new_w = min($dest_w, $orig_w);
467 $new_h = min($dest_h, $orig_h);
470 $new_w = (int) round( $new_h * $aspect_ratio );
474 $new_h = (int) round( $new_w / $aspect_ratio );
477 $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
479 $crop_w = round($new_w / $size_ratio);
480 $crop_h = round($new_h / $size_ratio);
482 if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
483 $crop = array( 'center', 'center' );
486 list( $x, $y ) = $crop;
488 if ( 'left' === $x ) {
490 } elseif ( 'right' === $x ) {
491 $s_x = $orig_w - $crop_w;
493 $s_x = floor( ( $orig_w - $crop_w ) / 2 );
496 if ( 'top' === $y ) {
498 } elseif ( 'bottom' === $y ) {
499 $s_y = $orig_h - $crop_h;
501 $s_y = floor( ( $orig_h - $crop_h ) / 2 );
504 // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
511 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
514 // if the resulting image would be the same size or larger we don't want to resize it
515 if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
519 // the return array matches the parameters to imagecopyresampled()
520 // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
521 return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
526 * Resize an image to make a thumbnail or intermediate size.
528 * The returned array has the file size, the image width, and image height. The
529 * filter 'image_make_intermediate_size' can be used to hook in and change the
530 * values of the returned array. The only parameter is the resized file path.
534 * @param string $file File path.
535 * @param int $width Image width.
536 * @param int $height Image height.
537 * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
538 * @return bool|array False, if no image was created. Metadata array on success.
540 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
541 if ( $width || $height ) {
542 $editor = wp_get_image_editor( $file );
544 if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
547 $resized_file = $editor->save();
549 if ( ! is_wp_error( $resized_file ) && $resized_file ) {
550 unset( $resized_file['path'] );
551 return $resized_file;
558 * Retrieve the image's intermediate size (resized) path, width, and height.
560 * The $size parameter can be an array with the width and height respectively.
561 * If the size matches the 'sizes' metadata array for width and height, then it
562 * will be used. If there is no direct match, then the nearest image size larger
563 * than the specified size will be used. If nothing is found, then the function
564 * will break out and return false.
566 * The metadata 'sizes' is used for compatible sizes that can be used for the
567 * parameter $size value.
569 * The url path will be given, when the $size parameter is a string.
571 * If you are passing an array for the $size, you should consider using
572 * add_image_size() so that a cropped version is generated. It's much more
573 * efficient than having to find the closest-sized image and then having the
574 * browser scale down the image.
577 * @see add_image_size()
579 * @param int $post_id Attachment ID for image.
580 * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
581 * @return bool|array False on failure or array of file path, width, and height on success.
583 function image_get_intermediate_size($post_id, $size='thumbnail') {
584 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
587 // get the best one for a specified set of dimensions
588 if ( is_array($size) && !empty($imagedata['sizes']) ) {
589 foreach ( $imagedata['sizes'] as $_size => $data ) {
590 // already cropped to width or height; so use this size
591 if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
592 $file = $data['file'];
593 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
594 return compact( 'file', 'width', 'height' );
596 // add to lookup table: area => size
597 $areas[$data['width'] * $data['height']] = $_size;
599 if ( !$size || !empty($areas) ) {
600 // find for the smallest image not smaller than the desired size
602 foreach ( $areas as $_size ) {
603 $data = $imagedata['sizes'][$_size];
604 if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
605 // Skip images with unexpectedly divergent aspect ratios (crops)
606 // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
607 $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
608 // 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
609 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'] ) ) )
611 // If we're still here, then we're going to use this size
612 $file = $data['file'];
613 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
614 return compact( 'file', 'width', 'height' );
620 if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
623 $data = $imagedata['sizes'][$size];
624 // include the full filesystem path of the intermediate file
625 if ( empty($data['path']) && !empty($data['file']) ) {
626 $file_url = wp_get_attachment_url($post_id);
627 $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
628 $data['url'] = path_join( dirname($file_url), $data['file'] );
634 * Get the available image sizes
636 * @return array Returns a filtered array of image size strings
638 function get_intermediate_image_sizes() {
639 global $_wp_additional_image_sizes;
640 $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
641 if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
642 $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
645 * Filter the list of intermediate image sizes.
649 * @param array $image_sizes An array of intermediate image sizes. Defaults
650 * are 'thumbnail', 'medium', 'large'.
652 return apply_filters( 'intermediate_image_sizes', $image_sizes );
656 * Retrieve an image to represent an attachment.
658 * A mime icon for files, thumbnail or intermediate size for images.
662 * @param int $attachment_id Image attachment ID.
663 * @param string $size Optional, default is 'thumbnail'.
664 * @param bool $icon Optional, default is false. Whether it is an icon.
665 * @return bool|array Returns an array (url, width, height), or false, if no image is available.
667 function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
669 // get a thumbnail or intermediate image if there is one
670 if ( $image = image_downsize($attachment_id, $size) )
675 if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
676 /** This filter is documented in wp-includes/post.php */
677 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
678 $src_file = $icon_dir . '/' . wp_basename($src);
679 @list($width, $height) = getimagesize($src_file);
681 if ( $src && $width && $height )
682 return array( $src, $width, $height );
687 * Get an HTML img element representing an image attachment
689 * While $size will accept an array, it is better to register a size with
690 * add_image_size() so that a cropped version is generated. It's much more
691 * efficient than having to find the closest-sized image and then having the
692 * browser scale down the image.
696 * @see add_image_size()
698 * @param int $attachment_id Image attachment ID.
699 * @param string|array $size Optional. Default 'thumbnail'.
700 * @param bool $icon Optional. Whether it is an icon. Default false.
701 * @param string|array $attr Optional. Attributes for the image markup. Default empty string.
702 * @return string HTML img element or empty string on failure.
704 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
707 $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
709 list($src, $width, $height) = $image;
710 $hwstring = image_hwstring($width, $height);
712 if ( is_array( $size_class ) ) {
713 $size_class = join( 'x', $size_class );
715 $attachment = get_post($attachment_id);
716 $default_attr = array(
718 'class' => "attachment-$size_class",
719 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
721 if ( empty($default_attr['alt']) )
722 $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
723 if ( empty($default_attr['alt']) )
724 $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
726 $attr = wp_parse_args($attr, $default_attr);
729 * Filter the list of attachment image attributes.
733 * @param array $attr Attributes for the image markup.
734 * @param WP_Post $attachment Image attachment post.
735 * @param string|array $size Requested size.
737 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
738 $attr = array_map( 'esc_attr', $attr );
739 $html = rtrim("<img $hwstring");
740 foreach ( $attr as $name => $value ) {
741 $html .= " $name=" . '"' . $value . '"';
750 * Adds a 'wp-post-image' class to post thumbnails
751 * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
752 * dynamically add/remove itself so as to only filter post thumbnails
755 * @param array $attr Attributes including src, class, alt, title
758 function _wp_post_thumbnail_class_filter( $attr ) {
759 $attr['class'] .= ' wp-post-image';
764 * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
768 function _wp_post_thumbnail_class_filter_add( $attr ) {
769 add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
773 * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
777 function _wp_post_thumbnail_class_filter_remove( $attr ) {
778 remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
781 add_shortcode('wp_caption', 'img_caption_shortcode');
782 add_shortcode('caption', 'img_caption_shortcode');
785 * The Caption shortcode.
787 * Allows a plugin to replace the content that would otherwise be returned. The
788 * filter is 'img_caption_shortcode' and passes an empty string, the attr
789 * parameter and the content parameter values.
791 * The supported attributes for the shortcode are 'id', 'align', 'width', and
796 * @param array $attr {
797 * Attributes of the caption shortcode.
799 * @type string $id ID of the div element for the caption.
800 * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
801 * 'aligncenter', alignright', 'alignnone'.
802 * @type int $width The width of the caption, in pixels.
803 * @type string $caption The caption text.
804 * @type string $class Additional class name(s) added to the caption container.
806 * @param string $content Optional. Shortcode content.
807 * @return string HTML content to display the caption.
809 function img_caption_shortcode( $attr, $content = null ) {
810 // New-style shortcode with the caption inside the shortcode with the link and image tags.
811 if ( ! isset( $attr['caption'] ) ) {
812 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
813 $content = $matches[1];
814 $attr['caption'] = trim( $matches[2] );
819 * Filter the default caption shortcode output.
821 * If the filtered output isn't empty, it will be used instead of generating
822 * the default caption template.
826 * @see img_caption_shortcode()
828 * @param string $output The caption output. Default empty.
829 * @param array $attr Attributes of the caption shortcode.
830 * @param string $content The image element, possibly wrapped in a hyperlink.
832 $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
836 $atts = shortcode_atts( array(
838 'align' => 'alignnone',
842 ), $attr, 'caption' );
844 $atts['width'] = (int) $atts['width'];
845 if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
848 if ( ! empty( $atts['id'] ) )
849 $atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';
851 $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
853 if ( current_theme_supports( 'html5', 'caption' ) ) {
854 return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
855 . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
858 $caption_width = 10 + $atts['width'];
861 * Filter the width of an image's caption.
863 * By default, the caption is 10 pixels greater than the width of the image,
864 * to prevent post content from running up against a floated image.
868 * @see img_caption_shortcode()
870 * @param int $caption_width Width of the caption in pixels. To remove this inline style,
872 * @param array $atts Attributes of the caption shortcode.
873 * @param string $content The image element, possibly wrapped in a hyperlink.
875 $caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
878 if ( $caption_width )
879 $style = 'style="width: ' . (int) $caption_width . 'px" ';
881 return '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
882 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
885 add_shortcode('gallery', 'gallery_shortcode');
888 * The Gallery shortcode.
890 * This implements the functionality of the Gallery Shortcode for displaying
891 * WordPress images on a post.
895 * @param array $attr {
896 * Attributes of the gallery shortcode.
898 * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
899 * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
900 * Accepts any valid SQL ORDERBY statement.
901 * @type int $id Post ID.
902 * @type string $itemtag HTML tag to use for each image in the gallery.
903 * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
904 * @type string $icontag HTML tag to use for each image's icon.
905 * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
906 * @type string $captiontag HTML tag to use for each image's caption.
907 * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
908 * @type int $columns Number of columns of images to display. Default 3.
909 * @type string $size Size of the images to display. Default 'thumbnail'.
910 * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
911 * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
912 * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
913 * @type string $link What to link each image to. Default empty (links to the attachment page).
914 * Accepts 'file', 'none'.
916 * @return string HTML content to display gallery.
918 function gallery_shortcode( $attr ) {
921 static $instance = 0;
924 if ( ! empty( $attr['ids'] ) ) {
925 // 'ids' is explicitly ordered, unless you specify otherwise.
926 if ( empty( $attr['orderby'] ) ) {
927 $attr['orderby'] = 'post__in';
929 $attr['include'] = $attr['ids'];
933 * Filter the default gallery shortcode output.
935 * If the filtered output isn't empty, it will be used instead of generating
936 * the default gallery template.
940 * @see gallery_shortcode()
942 * @param string $output The gallery output. Default empty.
943 * @param array $attr Attributes of the gallery shortcode.
945 $output = apply_filters( 'post_gallery', '', $attr );
946 if ( $output != '' ) {
950 $html5 = current_theme_supports( 'html5', 'gallery' );
951 $atts = shortcode_atts( array(
953 'orderby' => 'menu_order ID',
954 'id' => $post ? $post->ID : 0,
955 'itemtag' => $html5 ? 'figure' : 'dl',
956 'icontag' => $html5 ? 'div' : 'dt',
957 'captiontag' => $html5 ? 'figcaption' : 'dd',
959 'size' => 'thumbnail',
963 ), $attr, 'gallery' );
965 $id = intval( $atts['id'] );
967 if ( ! empty( $atts['include'] ) ) {
968 $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
970 $attachments = array();
971 foreach ( $_attachments as $key => $val ) {
972 $attachments[$val->ID] = $_attachments[$key];
974 } elseif ( ! empty( $atts['exclude'] ) ) {
975 $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'] ) );
977 $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
980 if ( empty( $attachments ) ) {
986 foreach ( $attachments as $att_id => $attachment ) {
987 $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
992 $itemtag = tag_escape( $atts['itemtag'] );
993 $captiontag = tag_escape( $atts['captiontag'] );
994 $icontag = tag_escape( $atts['icontag'] );
995 $valid_tags = wp_kses_allowed_html( 'post' );
996 if ( ! isset( $valid_tags[ $itemtag ] ) ) {
999 if ( ! isset( $valid_tags[ $captiontag ] ) ) {
1002 if ( ! isset( $valid_tags[ $icontag ] ) ) {
1006 $columns = intval( $atts['columns'] );
1007 $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
1008 $float = is_rtl() ? 'right' : 'left';
1010 $selector = "gallery-{$instance}";
1012 $gallery_style = '';
1015 * Filter whether to print default gallery styles.
1019 * @param bool $print Whether to print default gallery styles.
1020 * Defaults to false if the theme supports HTML5 galleries.
1021 * Otherwise, defaults to true.
1023 if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1025 <style type='text/css'>
1029 #{$selector} .gallery-item {
1033 width: {$itemwidth}%;
1036 border: 2px solid #cfcfcf;
1038 #{$selector} .gallery-caption {
1041 /* see gallery_shortcode() in wp-includes/media.php */
1045 $size_class = sanitize_html_class( $atts['size'] );
1046 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1049 * Filter the default gallery shortcode CSS styles.
1053 * @param string $gallery_style Default CSS styles and opening HTML div container
1054 * for the gallery shortcode output.
1056 $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1059 foreach ( $attachments as $id => $attachment ) {
1061 $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
1062 if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
1063 $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
1064 } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
1065 $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
1067 $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
1069 $image_meta = wp_get_attachment_metadata( $id );
1072 if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
1073 $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1075 $output .= "<{$itemtag} class='gallery-item'>";
1077 <{$icontag} class='gallery-icon {$orientation}'>
1080 if ( $captiontag && trim($attachment->post_excerpt) ) {
1082 <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
1083 " . wptexturize($attachment->post_excerpt) . "
1086 $output .= "</{$itemtag}>";
1087 if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1088 $output .= '<br style="clear: both" />';
1092 if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1094 <br style='clear: both' />";
1104 * Output the templates used by playlists.
1108 function wp_underscore_playlist_templates() {
1110 <script type="text/html" id="tmpl-wp-playlist-current-item">
1111 <# if ( data.image ) { #>
1112 <img src="{{ data.thumb.src }}"/>
1114 <div class="wp-playlist-caption">
1115 <span class="wp-playlist-item-meta wp-playlist-item-title">“{{ data.title }}”</span>
1116 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1117 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1120 <script type="text/html" id="tmpl-wp-playlist-item">
1121 <div class="wp-playlist-item">
1122 <a class="wp-playlist-caption" href="{{ data.src }}">
1123 {{ data.index ? ( data.index + '. ' ) : '' }}
1124 <# if ( data.caption ) { #>
1127 <span class="wp-playlist-item-title">“{{{ data.title }}}”</span>
1128 <# if ( data.artists && data.meta.artist ) { #>
1129 <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span>
1133 <# if ( data.meta.length_formatted ) { #>
1134 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1142 * Output and enqueue default scripts and styles for playlists.
1146 * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1148 function wp_playlist_scripts( $type ) {
1149 wp_enqueue_style( 'wp-mediaelement' );
1150 wp_enqueue_script( 'wp-playlist' );
1152 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1154 add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1155 add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1157 add_action( 'wp_playlist_scripts', 'wp_playlist_scripts' );
1160 * The playlist shortcode.
1162 * This implements the functionality of the playlist shortcode for displaying
1163 * a collection of WordPress audio or video files in a post.
1167 * @param array $attr {
1168 * Array of default playlist attributes.
1170 * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
1171 * @type string $order Designates ascending or descending order of items in the playlist.
1172 * Accepts 'ASC', 'DESC'. Default 'ASC'.
1173 * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
1174 * passed, this defaults to the order of the $ids array ('post__in').
1175 * Otherwise default is 'menu_order ID'.
1176 * @type int $id If an explicit $ids array is not present, this parameter
1177 * will determine which attachments are used for the playlist.
1178 * Default is the current post ID.
1179 * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
1180 * a playlist will be created from all $type attachments of $id.
1182 * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
1183 * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
1184 * @type bool $tracklist Whether to show or hide the playlist. Default true.
1185 * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
1186 * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
1187 * thumbnail). Default true.
1188 * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
1191 * @return string Playlist output. Empty string if the passed type is unsupported.
1193 function wp_playlist_shortcode( $attr ) {
1194 global $content_width;
1197 static $instance = 0;
1200 if ( ! empty( $attr['ids'] ) ) {
1201 // 'ids' is explicitly ordered, unless you specify otherwise.
1202 if ( empty( $attr['orderby'] ) ) {
1203 $attr['orderby'] = 'post__in';
1205 $attr['include'] = $attr['ids'];
1209 * Filter the playlist output.
1211 * Passing a non-empty value to the filter will short-circuit generation
1212 * of the default playlist output, returning the passed value instead.
1216 * @param string $output Playlist output. Default empty.
1217 * @param array $attr An array of shortcode attributes.
1219 $output = apply_filters( 'post_playlist', '', $attr );
1220 if ( $output != '' ) {
1224 $atts = shortcode_atts( array(
1227 'orderby' => 'menu_order ID',
1228 'id' => $post ? $post->ID : 0,
1232 'tracklist' => true,
1233 'tracknumbers' => true,
1236 ), $attr, 'playlist' );
1238 $id = intval( $atts['id'] );
1240 if ( $atts['type'] !== 'audio' ) {
1241 $atts['type'] = 'video';
1245 'post_status' => 'inherit',
1246 'post_type' => 'attachment',
1247 'post_mime_type' => $atts['type'],
1248 'order' => $atts['order'],
1249 'orderby' => $atts['orderby']
1252 if ( ! empty( $atts['include'] ) ) {
1253 $args['include'] = $atts['include'];
1254 $_attachments = get_posts( $args );
1256 $attachments = array();
1257 foreach ( $_attachments as $key => $val ) {
1258 $attachments[$val->ID] = $_attachments[$key];
1260 } elseif ( ! empty( $atts['exclude'] ) ) {
1261 $args['post_parent'] = $id;
1262 $args['exclude'] = $atts['exclude'];
1263 $attachments = get_children( $args );
1265 $args['post_parent'] = $id;
1266 $attachments = get_children( $args );
1269 if ( empty( $attachments ) ) {
1275 foreach ( $attachments as $att_id => $attachment ) {
1276 $output .= wp_get_attachment_link( $att_id ) . "\n";
1281 $outer = 22; // default padding and border of wrapper
1283 $default_width = 640;
1284 $default_height = 360;
1286 $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
1287 $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
1290 'type' => $atts['type'],
1291 // don't pass strings to JSON, will be truthy in JS
1292 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
1293 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
1294 'images' => wp_validate_boolean( $atts['images'] ),
1295 'artists' => wp_validate_boolean( $atts['artists'] ),
1299 foreach ( $attachments as $attachment ) {
1300 $url = wp_get_attachment_url( $attachment->ID );
1301 $ftype = wp_check_filetype( $url, wp_get_mime_types() );
1304 'type' => $ftype['type'],
1305 'title' => $attachment->post_title,
1306 'caption' => $attachment->post_excerpt,
1307 'description' => $attachment->post_content
1310 $track['meta'] = array();
1311 $meta = wp_get_attachment_metadata( $attachment->ID );
1312 if ( ! empty( $meta ) ) {
1314 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
1315 if ( ! empty( $meta[ $key ] ) ) {
1316 $track['meta'][ $key ] = $meta[ $key ];
1320 if ( 'video' === $atts['type'] ) {
1321 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1322 $width = $meta['width'];
1323 $height = $meta['height'];
1324 $theme_height = round( ( $height * $theme_width ) / $width );
1326 $width = $default_width;
1327 $height = $default_height;
1330 $track['dimensions'] = array(
1331 'original' => compact( 'width', 'height' ),
1333 'width' => $theme_width,
1334 'height' => $theme_height
1340 if ( $atts['images'] ) {
1341 $thumb_id = get_post_thumbnail_id( $attachment->ID );
1342 if ( ! empty( $thumb_id ) ) {
1343 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
1344 $track['image'] = compact( 'src', 'width', 'height' );
1345 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
1346 $track['thumb'] = compact( 'src', 'width', 'height' );
1348 $src = wp_mime_type_icon( $attachment->ID );
1351 $track['image'] = compact( 'src', 'width', 'height' );
1352 $track['thumb'] = compact( 'src', 'width', 'height' );
1358 $data['tracks'] = $tracks;
1360 $safe_type = esc_attr( $atts['type'] );
1361 $safe_style = esc_attr( $atts['style'] );
1365 if ( 1 === $instance ) {
1367 * Print and enqueue playlist scripts, styles, and JavaScript templates.
1371 * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
1372 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
1374 do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
1376 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
1377 <?php if ( 'audio' === $atts['type'] ): ?>
1378 <div class="wp-playlist-current-item"></div>
1380 <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
1381 echo (int) $theme_width;
1382 ?>"<?php if ( 'video' === $safe_type ):
1383 echo ' height="', (int) $theme_height, '"';
1385 echo ' style="visibility: hidden"';
1386 endif; ?>></<?php echo $safe_type ?>>
1387 <div class="wp-playlist-next"></div>
1388 <div class="wp-playlist-prev"></div>
1391 foreach ( $attachments as $att_id => $attachment ) {
1392 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
1396 <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
1399 return ob_get_clean();
1401 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
1404 * Provide a No-JS Flash fallback as a last resort for audio / video
1408 * @param string $url
1409 * @return string Fallback HTML
1411 function wp_mediaelement_fallback( $url ) {
1413 * Filter the Mediaelement fallback output for no-JS.
1417 * @param string $output Fallback output for no-JS.
1418 * @param string $url Media file URL.
1420 return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
1424 * Return a filtered list of WP-supported audio formats.
1429 function wp_get_audio_extensions() {
1431 * Filter the list of supported audio formats.
1435 * @param array $extensions An array of support audio formats. Defaults are
1436 * 'mp3', 'ogg', 'wma', 'm4a', 'wav'.
1438 return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
1442 * Return useful keys to use to lookup data from an attachment's stored metadata.
1446 * @param WP_Post $attachment The current attachment, provided for context.
1447 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
1448 * @return array Key/value pairs of field keys to labels.
1450 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
1452 'artist' => __( 'Artist' ),
1453 'album' => __( 'Album' ),
1456 if ( 'display' === $context ) {
1457 $fields['genre'] = __( 'Genre' );
1458 $fields['year'] = __( 'Year' );
1459 $fields['length_formatted'] = _x( 'Length', 'video or audio' );
1460 } elseif ( 'js' === $context ) {
1461 $fields['bitrate'] = __( 'Bitrate' );
1462 $fields['bitrate_mode'] = __( 'Bitrate Mode' );
1466 * Filter the editable list of keys to look up data from an attachment's metadata.
1470 * @param array $fields Key/value pairs of field keys to labels.
1471 * @param WP_Post $attachment Attachment object.
1472 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
1474 return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
1477 * The Audio shortcode.
1479 * This implements the functionality of the Audio Shortcode for displaying
1480 * WordPress mp3s in a post.
1484 * @param array $attr {
1485 * Attributes of the audio shortcode.
1487 * @type string $src URL to the source of the audio file. Default empty.
1488 * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
1489 * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
1490 * @type string $preload The 'preload' attribute for the `<audio>` element. Default empty.
1491 * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
1492 * @type string $id The 'id' attribute for the `<audio>` element. Default 'audio-{$post_id}-{$instances}'.
1493 * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
1495 * @param string $content Optional. Shortcode content.
1496 * @return string HTML content to display audio.
1498 function wp_audio_shortcode( $attr, $content = '' ) {
1499 $post_id = get_post() ? get_the_ID() : 0;
1501 static $instances = 0;
1505 * Filter the default audio shortcode output.
1507 * If the filtered output isn't empty, it will be used instead of generating the default audio template.
1511 * @param string $html Empty variable to be replaced with shortcode markup.
1512 * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
1513 * @param string $content Shortcode content.
1514 * @param int $instances Unique numeric ID of this audio shortcode instance.
1516 $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instances );
1517 if ( '' !== $override ) {
1523 $default_types = wp_get_audio_extensions();
1524 $defaults_atts = array(
1530 foreach ( $default_types as $type ) {
1531 $defaults_atts[$type] = '';
1534 $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
1537 if ( ! empty( $atts['src'] ) ) {
1538 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
1539 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1540 return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
1543 array_unshift( $default_types, 'src' );
1545 foreach ( $default_types as $ext ) {
1546 if ( ! empty( $atts[ $ext ] ) ) {
1547 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
1548 if ( strtolower( $type['ext'] ) === $ext ) {
1556 $audios = get_attached_media( 'audio', $post_id );
1557 if ( empty( $audios ) ) {
1561 $audio = reset( $audios );
1562 $atts['src'] = wp_get_attachment_url( $audio->ID );
1563 if ( empty( $atts['src'] ) ) {
1567 array_unshift( $default_types, 'src' );
1571 * Filter the media library used for the audio shortcode.
1575 * @param string $library Media library used for the audio shortcode.
1577 $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
1578 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1579 wp_enqueue_style( 'wp-mediaelement' );
1580 wp_enqueue_script( 'wp-mediaelement' );
1584 * Filter the class attribute for the audio shortcode output container.
1588 * @param string $class CSS class or list of space-separated classes.
1591 'class' => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
1592 'id' => sprintf( 'audio-%d-%d', $post_id, $instances ),
1593 'loop' => wp_validate_boolean( $atts['loop'] ),
1594 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
1595 'preload' => $atts['preload'],
1596 'style' => 'width: 100%; visibility: hidden;',
1599 // These ones should just be omitted altogether if they are blank
1600 foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
1601 if ( empty( $html_atts[$a] ) ) {
1602 unset( $html_atts[$a] );
1606 $attr_strings = array();
1607 foreach ( $html_atts as $k => $v ) {
1608 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1612 if ( 'mediaelement' === $library && 1 === $instances ) {
1613 $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
1615 $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
1618 $source = '<source type="%s" src="%s" />';
1619 foreach ( $default_types as $fallback ) {
1620 if ( ! empty( $atts[ $fallback ] ) ) {
1621 if ( empty( $fileurl ) ) {
1622 $fileurl = $atts[ $fallback ];
1624 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
1625 $url = add_query_arg( '_', $instances, $atts[ $fallback ] );
1626 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1630 if ( 'mediaelement' === $library ) {
1631 $html .= wp_mediaelement_fallback( $fileurl );
1633 $html .= '</audio>';
1636 * Filter the audio shortcode output.
1640 * @param string $html Audio shortcode HTML output.
1641 * @param array $atts Array of audio shortcode attributes.
1642 * @param string $audio Audio file.
1643 * @param int $post_id Post ID.
1644 * @param string $library Media library used for the audio shortcode.
1646 return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
1648 add_shortcode( 'audio', 'wp_audio_shortcode' );
1651 * Return a filtered list of WP-supported video formats
1656 function wp_get_video_extensions() {
1658 * Filter the list of supported video formats.
1662 * @param array $extensions An array of support video formats. Defaults are
1663 * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
1665 return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
1669 * The Video shortcode.
1671 * This implements the functionality of the Video Shortcode for displaying
1672 * WordPress mp4s in a post.
1676 * @param array $attr {
1677 * Attributes of the shortcode.
1679 * @type string $src URL to the source of the video file. Default empty.
1680 * @type int $height Height of the video embed in pixels. Default 360.
1681 * @type int $width Width of the video embed in pixels. Default $content_width or 640.
1682 * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
1683 * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
1684 * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
1685 * @type string $preload The 'preload' attribute for the `<video>` element.
1686 * Default 'metadata'.
1687 * @type string $class The 'class' attribute for the `<video>` element.
1688 * Default 'wp-video-shortcode'.
1689 * @type string $id The 'id' attribute for the `<video>` element.
1690 * Default 'video-{$post_id}-{$instances}'.
1692 * @param string $content Optional. Shortcode content.
1693 * @return string HTML content to display video.
1695 function wp_video_shortcode( $attr, $content = '' ) {
1696 global $content_width;
1697 $post_id = get_post() ? get_the_ID() : 0;
1699 static $instances = 0;
1703 * Filter the default video shortcode output.
1705 * If the filtered output isn't empty, it will be used instead of generating
1706 * the default video template.
1710 * @see wp_video_shortcode()
1712 * @param string $html Empty variable to be replaced with shortcode markup.
1713 * @param array $attr Attributes of the video shortcode.
1714 * @param string $content Video shortcode content.
1715 * @param int $instances Unique numeric ID of this video shortcode instance.
1717 $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instances );
1718 if ( '' !== $override ) {
1724 $default_types = wp_get_video_extensions();
1725 $defaults_atts = array(
1730 'preload' => 'metadata',
1735 foreach ( $default_types as $type ) {
1736 $defaults_atts[$type] = '';
1739 $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
1742 // shrink the video so it isn't huge in the admin
1743 if ( $atts['width'] > $defaults_atts['width'] ) {
1744 $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
1745 $atts['width'] = $defaults_atts['width'];
1748 // if the video is bigger than the theme
1749 if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
1750 $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
1751 $atts['width'] = $content_width;
1755 $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
1758 if ( ! empty( $atts['src'] ) ) {
1759 if ( ! preg_match( $yt_pattern, $atts['src'] ) ) {
1760 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
1761 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1762 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
1766 array_unshift( $default_types, 'src' );
1768 foreach ( $default_types as $ext ) {
1769 if ( ! empty( $atts[ $ext ] ) ) {
1770 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
1771 if ( strtolower( $type['ext'] ) === $ext ) {
1779 $videos = get_attached_media( 'video', $post_id );
1780 if ( empty( $videos ) ) {
1784 $video = reset( $videos );
1785 $atts['src'] = wp_get_attachment_url( $video->ID );
1786 if ( empty( $atts['src'] ) ) {
1790 array_unshift( $default_types, 'src' );
1794 * Filter the media library used for the video shortcode.
1798 * @param string $library Media library used for the video shortcode.
1800 $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
1801 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1802 wp_enqueue_style( 'wp-mediaelement' );
1803 wp_enqueue_script( 'wp-mediaelement' );
1807 * Filter the class attribute for the video shortcode output container.
1811 * @param string $class CSS class or list of space-separated classes.
1814 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
1815 'id' => sprintf( 'video-%d-%d', $post_id, $instances ),
1816 'width' => absint( $atts['width'] ),
1817 'height' => absint( $atts['height'] ),
1818 'poster' => esc_url( $atts['poster'] ),
1819 'loop' => wp_validate_boolean( $atts['loop'] ),
1820 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
1821 'preload' => $atts['preload'],
1824 // These ones should just be omitted altogether if they are blank
1825 foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
1826 if ( empty( $html_atts[$a] ) ) {
1827 unset( $html_atts[$a] );
1831 $attr_strings = array();
1832 foreach ( $html_atts as $k => $v ) {
1833 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1837 if ( 'mediaelement' === $library && 1 === $instances ) {
1838 $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
1840 $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
1843 $source = '<source type="%s" src="%s" />';
1844 foreach ( $default_types as $fallback ) {
1845 if ( ! empty( $atts[ $fallback ] ) ) {
1846 if ( empty( $fileurl ) ) {
1847 $fileurl = $atts[ $fallback ];
1849 if ( 'src' === $fallback && preg_match( $yt_pattern, $atts['src'] ) ) {
1850 $type = array( 'type' => 'video/youtube' );
1852 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
1854 $url = add_query_arg( '_', $instances, $atts[ $fallback ] );
1855 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1859 if ( ! empty( $content ) ) {
1860 if ( false !== strpos( $content, "\n" ) ) {
1861 $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
1863 $html .= trim( $content );
1866 if ( 'mediaelement' === $library ) {
1867 $html .= wp_mediaelement_fallback( $fileurl );
1869 $html .= '</video>';
1872 if ( ! empty( $atts['width'] ) ) {
1873 $width_rule = sprintf( 'width: %dpx; ', $atts['width'] );
1875 $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
1878 * Filter the output of the video shortcode.
1882 * @param string $output Video shortcode HTML output.
1883 * @param array $atts Array of video shortcode attributes.
1884 * @param string $video Video file.
1885 * @param int $post_id Post ID.
1886 * @param string $library Media library used for the video shortcode.
1888 return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
1890 add_shortcode( 'video', 'wp_video_shortcode' );
1893 * Display previous image link that has the same post parent.
1896 * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
1897 * @param string $text Optional, default is false. If included, link will reflect $text variable.
1898 * @return string HTML content.
1900 function previous_image_link($size = 'thumbnail', $text = false) {
1901 adjacent_image_link(true, $size, $text);
1905 * Display next image link that has the same post parent.
1908 * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
1909 * @param string $text Optional, default is false. If included, link will reflect $text variable.
1910 * @return string HTML content.
1912 function next_image_link($size = 'thumbnail', $text = false) {
1913 adjacent_image_link(false, $size, $text);
1917 * Display next or previous image link that has the same post parent.
1919 * Retrieves the current attachment object from the $post global.
1923 * @param bool $prev Optional. Default is true to display previous link, false for next.
1925 function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
1927 $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' ) ) );
1929 foreach ( $attachments as $k => $attachment ) {
1930 if ( $attachment->ID == $post->ID ) {
1938 if ( $attachments ) {
1939 $k = $prev ? $k - 1 : $k + 1;
1941 if ( isset( $attachments[ $k ] ) ) {
1942 $attachment_id = $attachments[ $k ]->ID;
1943 $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
1947 $adjacent = $prev ? 'previous' : 'next';
1950 * Filter the adjacent image link.
1952 * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
1953 * either 'next', or 'previous'.
1957 * @param string $output Adjacent image HTML markup.
1958 * @param int $attachment_id Attachment ID
1959 * @param string $size Image size.
1960 * @param string $text Link text.
1962 echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
1966 * Retrieve taxonomies attached to the attachment.
1970 * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
1971 * @return array Empty array on failure. List of taxonomies on success.
1973 function get_attachment_taxonomies($attachment) {
1974 if ( is_int( $attachment ) )
1975 $attachment = get_post($attachment);
1976 else if ( is_array($attachment) )
1977 $attachment = (object) $attachment;
1979 if ( ! is_object($attachment) )
1982 $filename = basename($attachment->guid);
1984 $objects = array('attachment');
1986 if ( false !== strpos($filename, '.') )
1987 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
1988 if ( !empty($attachment->post_mime_type) ) {
1989 $objects[] = 'attachment:' . $attachment->post_mime_type;
1990 if ( false !== strpos($attachment->post_mime_type, '/') )
1991 foreach ( explode('/', $attachment->post_mime_type) as $token )
1992 if ( !empty($token) )
1993 $objects[] = "attachment:$token";
1996 $taxonomies = array();
1997 foreach ( $objects as $object )
1998 if ( $taxes = get_object_taxonomies($object) )
1999 $taxonomies = array_merge($taxonomies, $taxes);
2001 return array_unique($taxonomies);
2005 * Return all of the taxonomy names that are registered for attachments.
2007 * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
2010 * @see get_attachment_taxonomies()
2012 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
2013 * @return array The names of all taxonomy of $object_type.
2015 function get_taxonomies_for_attachments( $output = 'names' ) {
2016 $taxonomies = array();
2017 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
2018 foreach ( $taxonomy->object_type as $object_type ) {
2019 if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
2020 if ( 'names' == $output )
2021 $taxonomies[] = $taxonomy->name;
2023 $taxonomies[ $taxonomy->name ] = $taxonomy;
2033 * Create new GD image resource with transparency support
2034 * @TODO: Deprecate if possible.
2038 * @param int $width Image width
2039 * @param int $height Image height
2040 * @return resource resource
2042 function wp_imagecreatetruecolor($width, $height) {
2043 $img = imagecreatetruecolor($width, $height);
2044 if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
2045 imagealphablending($img, false);
2046 imagesavealpha($img, true);
2052 * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
2055 * @see WP_Embed::register_handler()
2057 * @global WP_Embed $wp_embed
2059 * @param string $regex
2060 * @param callable $callback
2061 * @param int $priority
2063 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
2065 $wp_embed->register_handler( $id, $regex, $callback, $priority );
2069 * Unregister a previously registered embed handler.
2072 * @see WP_Embed::unregister_handler()
2074 * @global WP_Embed $wp_embed
2076 * @param int $priority
2078 function wp_embed_unregister_handler( $id, $priority = 10 ) {
2080 $wp_embed->unregister_handler( $id, $priority );
2084 * Create default array of embed parameters.
2086 * The width defaults to the content width as specified by the theme. If the
2087 * theme does not specify a content width, then 500px is used.
2089 * The default height is 1.5 times the width, or 1000px, whichever is smaller.
2091 * The 'embed_defaults' filter can be used to adjust either of these values.
2095 * @param string $url Optional. The URL that should be embedded. Default empty.
2097 * @return array Default embed parameters.
2099 function wp_embed_defaults( $url = '' ) {
2100 if ( ! empty( $GLOBALS['content_width'] ) )
2101 $width = (int) $GLOBALS['content_width'];
2103 if ( empty( $width ) )
2106 $height = min( ceil( $width * 1.5 ), 1000 );
2109 * Filter the default array of embed dimensions.
2113 * @param int $width Width of the embed in pixels.
2114 * @param int $height Height of the embed in pixels.
2115 * @param string $url The URL that should be embedded.
2117 return apply_filters( 'embed_defaults', compact( 'width', 'height' ), $url );
2121 * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
2125 * @param int $example_width The width of an example embed.
2126 * @param int $example_height The height of an example embed.
2127 * @param int $max_width The maximum allowed width.
2128 * @param int $max_height The maximum allowed height.
2129 * @return array The maximum possible width and height based on the example ratio.
2131 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
2132 $example_width = (int) $example_width;
2133 $example_height = (int) $example_height;
2134 $max_width = (int) $max_width;
2135 $max_height = (int) $max_height;
2137 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
2141 * Attempts to fetch the embed HTML for a provided URL using oEmbed.
2146 * @param string $url The URL that should be embedded.
2147 * @param array $args Additional arguments and parameters.
2148 * @return false|string False on failure or the embed HTML on success.
2150 function wp_oembed_get( $url, $args = '' ) {
2151 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2152 $oembed = _wp_oembed_get_object();
2153 return $oembed->get_html( $url, $args );
2157 * Adds a URL format and oEmbed provider URL pair.
2162 * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
2163 * @param string $provider The URL to the oEmbed provider.
2164 * @param boolean $regex Whether the $format parameter is in a regex format.
2166 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
2167 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2169 if ( did_action( 'plugins_loaded' ) ) {
2170 $oembed = _wp_oembed_get_object();
2171 $oembed->providers[$format] = array( $provider, $regex );
2173 WP_oEmbed::_add_provider_early( $format, $provider, $regex );
2178 * Removes an oEmbed provider.
2183 * @param string $format The URL format for the oEmbed provider to remove.
2185 function wp_oembed_remove_provider( $format ) {
2186 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2188 if ( did_action( 'plugins_loaded' ) ) {
2189 $oembed = _wp_oembed_get_object();
2191 if ( isset( $oembed->providers[ $format ] ) ) {
2192 unset( $oembed->providers[ $format ] );
2196 WP_oEmbed::_remove_provider_early( $format );
2203 * Determines if default embed handlers should be loaded.
2205 * Checks to make sure that the embeds library hasn't already been loaded. If
2206 * it hasn't, then it will load the embeds library.
2210 function wp_maybe_load_embeds() {
2212 * Filter whether to load the default embed handlers.
2214 * Returning a falsey value will prevent loading the default embed handlers.
2218 * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
2220 if ( ! apply_filters( 'load_default_embeds', true ) ) {
2224 wp_embed_register_handler( 'youtube_embed_url', '#https?://(www.)?youtube\.com/embed/([^/]+)#i', 'wp_embed_handler_youtube' );
2226 wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
2229 * Filter the audio embed handler callback.
2233 * @param callback $handler Audio embed handler callback function.
2235 wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
2238 * Filter the video embed handler callback.
2242 * @param callback $handler Video embed handler callback function.
2244 wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
2248 * The Google Video embed handler callback. Google Video does not support oEmbed.
2250 * @see WP_Embed::register_handler()
2251 * @see WP_Embed::shortcode()
2253 * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
2254 * @param array $attr Embed attributes.
2255 * @param string $url The original URL that was matched by the regex.
2256 * @param array $rawattr The original unmodified attributes.
2257 * @return string The embed HTML.
2259 function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
2260 // If the user supplied a fixed width AND height, use it
2261 if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
2262 $width = (int) $rawattr['width'];
2263 $height = (int) $rawattr['height'];
2265 list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
2269 * Filter the Google Video embed output.
2273 * @param string $html Google Video HTML embed markup.
2274 * @param array $matches The regex matches from the provided regex.
2275 * @param array $attr An array of embed attributes.
2276 * @param string $url The original URL that was matched by the regex.
2277 * @param array $rawattr The original unmodified attributes.
2279 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 );
2283 * YouTube embed handler callback.
2285 * Catches URLs that can be parsed but aren't supported by oEmbed.
2289 * @param array $matches The regex matches from the provided regex when calling
2290 * {@see wp_embed_register_handler()}.
2291 * @param array $attr Embed attributes.
2292 * @param string $url The original URL that was matched by the regex.
2293 * @param array $rawattr The original unmodified attributes.
2294 * @return string The embed HTML.
2296 function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
2298 $embed = $wp_embed->autoembed( "https://youtube.com/watch?v={$matches[2]}" );
2300 * Filter the YoutTube embed output.
2304 * @see wp_embed_handler_youtube()
2306 * @param string $embed YouTube embed output.
2307 * @param array $attr An array of embed attributes.
2308 * @param string $url The original URL that was matched by the regex.
2309 * @param array $rawattr The original unmodified attributes.
2311 return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
2315 * Audio embed handler callback.
2319 * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
2320 * @param array $attr Embed attributes.
2321 * @param string $url The original URL that was matched by the regex.
2322 * @param array $rawattr The original unmodified attributes.
2323 * @return string The embed HTML.
2325 function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
2326 $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
2329 * Filter the audio embed output.
2333 * @param string $audio Audio embed output.
2334 * @param array $attr An array of embed attributes.
2335 * @param string $url The original URL that was matched by the regex.
2336 * @param array $rawattr The original unmodified attributes.
2338 return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
2342 * Video embed handler callback.
2346 * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
2347 * @param array $attr Embed attributes.
2348 * @param string $url The original URL that was matched by the regex.
2349 * @param array $rawattr The original unmodified attributes.
2350 * @return string The embed HTML.
2352 function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
2354 if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
2355 $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
2356 $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
2358 $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
2361 * Filter the video embed output.
2365 * @param string $video Video embed output.
2366 * @param array $attr An array of embed attributes.
2367 * @param string $url The original URL that was matched by the regex.
2368 * @param array $rawattr The original unmodified attributes.
2370 return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
2374 * Converts a shorthand byte value to an integer byte value.
2378 * @param string $size A shorthand byte value.
2379 * @return int An integer byte value.
2381 function wp_convert_hr_to_bytes( $size ) {
2382 $size = strtolower( $size );
2383 $bytes = (int) $size;
2384 if ( strpos( $size, 'k' ) !== false )
2385 $bytes = intval( $size ) * 1024;
2386 elseif ( strpos( $size, 'm' ) !== false )
2387 $bytes = intval($size) * 1024 * 1024;
2388 elseif ( strpos( $size, 'g' ) !== false )
2389 $bytes = intval( $size ) * 1024 * 1024 * 1024;
2394 * Determine the maximum upload size allowed in php.ini.
2398 * @return int Allowed upload size.
2400 function wp_max_upload_size() {
2401 $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2402 $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2405 * Filter the maximum upload size allowed in php.ini.
2409 * @param int $size Max upload size limit in bytes.
2410 * @param int $u_bytes Maximum upload filesize in bytes.
2411 * @param int $p_bytes Maximum size of POST data in bytes.
2413 return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2417 * Returns a WP_Image_Editor instance and loads file into it.
2422 * @param string $path Path to file to load
2423 * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
2424 * @return WP_Image_Editor|WP_Error
2426 function wp_get_image_editor( $path, $args = array() ) {
2427 $args['path'] = $path;
2429 if ( ! isset( $args['mime_type'] ) ) {
2430 $file_info = wp_check_filetype( $args['path'] );
2432 // If $file_info['type'] is false, then we let the editor attempt to
2433 // figure out the file type, rather than forcing a failure based on extension.
2434 if ( isset( $file_info ) && $file_info['type'] )
2435 $args['mime_type'] = $file_info['type'];
2438 $implementation = _wp_image_editor_choose( $args );
2440 if ( $implementation ) {
2441 $editor = new $implementation( $path );
2442 $loaded = $editor->load();
2444 if ( is_wp_error( $loaded ) )
2450 return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
2454 * Tests whether there is an editor that supports a given mime type or methods.
2459 * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
2460 * @return boolean true if an eligible editor is found; false otherwise
2462 function wp_image_editor_supports( $args = array() ) {
2463 return (bool) _wp_image_editor_choose( $args );
2467 * Tests which editors are capable of supporting the request.
2472 * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
2473 * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
2475 function _wp_image_editor_choose( $args = array() ) {
2476 require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
2477 require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
2478 require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
2481 * Filter the list of image editing library classes.
2485 * @param array $image_editors List of available image editors. Defaults are
2486 * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
2488 $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
2490 foreach ( $implementations as $implementation ) {
2491 if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
2494 if ( isset( $args['mime_type'] ) &&
2496 array( $implementation, 'supports_mime_type' ),
2497 $args['mime_type'] ) ) {
2501 if ( isset( $args['methods'] ) &&
2502 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
2506 return $implementation;
2513 * Prints default plupload arguments.
2517 function wp_plupload_default_settings() {
2520 $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
2521 if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
2524 $max_upload_size = wp_max_upload_size();
2527 'runtimes' => 'html5,flash,silverlight,html4',
2528 'file_data_name' => 'async-upload', // key passed to $_FILE.
2529 'url' => admin_url( 'async-upload.php', 'relative' ),
2530 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
2531 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
2533 'max_file_size' => $max_upload_size . 'b',
2537 // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
2538 // when enabled. See #29602.
2539 if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
2540 strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
2542 $defaults['multi_selection'] = false;
2546 * Filter the Plupload default settings.
2550 * @param array $defaults Default Plupload settings array.
2552 $defaults = apply_filters( 'plupload_default_settings', $defaults );
2555 'action' => 'upload-attachment',
2559 * Filter the Plupload default parameters.
2563 * @param array $params Default Plupload parameters array.
2565 $params = apply_filters( 'plupload_default_params', $params );
2566 $params['_wpnonce'] = wp_create_nonce( 'media-form' );
2567 $defaults['multipart_params'] = $params;
2570 'defaults' => $defaults,
2572 'mobile' => wp_is_mobile(),
2573 'supported' => _device_can_upload(),
2575 'limitExceeded' => is_multisite() && ! is_upload_space_available()
2578 $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
2581 $script = "$data\n$script";
2583 $wp_scripts->add_data( 'wp-plupload', 'data', $script );
2585 add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
2588 * Prepares an attachment post object for JS, where it is expected
2589 * to be JSON-encoded and fit into an Attachment model.
2593 * @param mixed $attachment Attachment ID or object.
2594 * @return array Array of attachment details.
2596 function wp_prepare_attachment_for_js( $attachment ) {
2597 if ( ! $attachment = get_post( $attachment ) )
2600 if ( 'attachment' != $attachment->post_type )
2603 $meta = wp_get_attachment_metadata( $attachment->ID );
2604 if ( false !== strpos( $attachment->post_mime_type, '/' ) )
2605 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
2607 list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
2609 $attachment_url = wp_get_attachment_url( $attachment->ID );
2612 'id' => $attachment->ID,
2613 'title' => $attachment->post_title,
2614 'filename' => wp_basename( $attachment->guid ),
2615 'url' => $attachment_url,
2616 'link' => get_attachment_link( $attachment->ID ),
2617 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
2618 'author' => $attachment->post_author,
2619 'description' => $attachment->post_content,
2620 'caption' => $attachment->post_excerpt,
2621 'name' => $attachment->post_name,
2622 'status' => $attachment->post_status,
2623 'uploadedTo' => $attachment->post_parent,
2624 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
2625 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
2626 'menuOrder' => $attachment->menu_order,
2627 'mime' => $attachment->post_mime_type,
2629 'subtype' => $subtype,
2630 'icon' => wp_mime_type_icon( $attachment->ID ),
2631 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
2637 'editLink' => false,
2641 $author = new WP_User( $attachment->post_author );
2642 $response['authorName'] = $author->display_name;
2644 if ( $attachment->post_parent ) {
2645 $post_parent = get_post( $attachment->post_parent );
2647 $post_parent = false;
2650 if ( $post_parent ) {
2651 $parent_type = get_post_type_object( $post_parent->post_type );
2652 if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
2653 $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
2655 $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
2658 $attached_file = get_attached_file( $attachment->ID );
2659 if ( file_exists( $attached_file ) ) {
2660 $bytes = filesize( $attached_file );
2661 $response['filesizeInBytes'] = $bytes;
2662 $response['filesizeHumanReadable'] = size_format( $bytes );
2665 if ( current_user_can( 'edit_post', $attachment->ID ) ) {
2666 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
2667 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
2668 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
2671 if ( current_user_can( 'delete_post', $attachment->ID ) )
2672 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
2674 if ( $meta && 'image' === $type ) {
2677 /** This filter is documented in wp-admin/includes/media.php */
2678 $possible_sizes = apply_filters( 'image_size_names_choose', array(
2679 'thumbnail' => __('Thumbnail'),
2680 'medium' => __('Medium'),
2681 'large' => __('Large'),
2682 'full' => __('Full Size'),
2684 unset( $possible_sizes['full'] );
2686 // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
2687 // First: run the image_downsize filter. If it returns something, we can use its data.
2688 // If the filter does not return something, then image_downsize() is just an expensive
2689 // way to check the image metadata, which we do second.
2690 foreach ( $possible_sizes as $size => $label ) {
2692 /** This filter is documented in wp-includes/media.php */
2693 if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
2694 if ( ! $downsize[3] )
2696 $sizes[ $size ] = array(
2697 'height' => $downsize[2],
2698 'width' => $downsize[1],
2699 'url' => $downsize[0],
2700 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
2702 } elseif ( isset( $meta['sizes'][ $size ] ) ) {
2703 if ( ! isset( $base_url ) )
2704 $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
2706 // Nothing from the filter, so consult image metadata if we have it.
2707 $size_meta = $meta['sizes'][ $size ];
2709 // We have the actual image size, but might need to further constrain it if content_width is narrower.
2710 // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
2711 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
2713 $sizes[ $size ] = array(
2714 'height' => $height,
2716 'url' => $base_url . $size_meta['file'],
2717 'orientation' => $height > $width ? 'portrait' : 'landscape',
2722 $sizes['full'] = array( 'url' => $attachment_url );
2724 if ( isset( $meta['height'], $meta['width'] ) ) {
2725 $sizes['full']['height'] = $meta['height'];
2726 $sizes['full']['width'] = $meta['width'];
2727 $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
2730 $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
2731 } elseif ( $meta && 'video' === $type ) {
2732 if ( isset( $meta['width'] ) )
2733 $response['width'] = (int) $meta['width'];
2734 if ( isset( $meta['height'] ) )
2735 $response['height'] = (int) $meta['height'];
2738 if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
2739 if ( isset( $meta['length_formatted'] ) )
2740 $response['fileLength'] = $meta['length_formatted'];
2742 $response['meta'] = array();
2743 foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
2744 $response['meta'][ $key ] = false;
2746 if ( ! empty( $meta[ $key ] ) ) {
2747 $response['meta'][ $key ] = $meta[ $key ];
2751 $id = get_post_thumbnail_id( $attachment->ID );
2752 if ( ! empty( $id ) ) {
2753 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
2754 $response['image'] = compact( 'src', 'width', 'height' );
2755 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
2756 $response['thumb'] = compact( 'src', 'width', 'height' );
2758 $src = wp_mime_type_icon( $attachment->ID );
2761 $response['image'] = compact( 'src', 'width', 'height' );
2762 $response['thumb'] = compact( 'src', 'width', 'height' );
2766 if ( function_exists('get_compat_media_markup') )
2767 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
2770 * Filter the attachment data prepared for JavaScript.
2774 * @param array $response Array of prepared attachment data.
2775 * @param int|object $attachment Attachment ID or object.
2776 * @param array $meta Array of attachment meta data.
2778 return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
2782 * Enqueues all scripts, styles, settings, and templates necessary to use
2783 * all media JS APIs.
2787 function wp_enqueue_media( $args = array() ) {
2789 // Enqueue me just once per page, please.
2790 if ( did_action( 'wp_enqueue_media' ) )
2793 global $content_width, $wpdb, $wp_locale;
2798 $args = wp_parse_args( $args, $defaults );
2800 // We're going to pass the old thickbox media tabs to `media_upload_tabs`
2801 // to ensure plugins will work. We will then unset those tabs.
2803 // handler action suffix => tab label
2810 /** This filter is documented in wp-admin/includes/media.php */
2811 $tabs = apply_filters( 'media_upload_tabs', $tabs );
2812 unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
2815 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
2816 'align' => get_option( 'image_default_align' ), // empty default
2817 'size' => get_option( 'image_default_size' ), // empty default
2820 $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
2821 $mimes = get_allowed_mime_types();
2822 $ext_mimes = array();
2823 foreach ( $exts as $ext ) {
2824 foreach ( $mimes as $ext_preg => $mime_match ) {
2825 if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
2826 $ext_mimes[ $ext ] = $mime_match;
2832 $has_audio = $wpdb->get_var( "
2835 WHERE post_type = 'attachment'
2836 AND post_mime_type LIKE 'audio%'
2839 $has_video = $wpdb->get_var( "
2842 WHERE post_type = 'attachment'
2843 AND post_mime_type LIKE 'video%'
2846 $months = $wpdb->get_results( $wpdb->prepare( "
2847 SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
2849 WHERE post_type = %s
2850 ORDER BY post_date DESC
2851 ", 'attachment' ) );
2852 foreach ( $months as $month_year ) {
2853 $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
2858 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
2859 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
2860 /** This filter is documented in wp-admin/includes/media.php */
2861 'captions' => ! apply_filters( 'disable_captions', '' ),
2863 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
2868 'defaultProps' => $props,
2869 'attachmentCounts' => array(
2870 'audio' => ( $has_audio ) ? 1 : 0,
2871 'video' => ( $has_video ) ? 1 : 0
2873 'embedExts' => $exts,
2874 'embedMimes' => $ext_mimes,
2875 'contentWidth' => $content_width,
2876 'months' => $months,
2877 'mediaTrash' => MEDIA_TRASH ? 1 : 0
2881 if ( isset( $args['post'] ) ) {
2882 $post = get_post( $args['post'] );
2883 $settings['post'] = array(
2885 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
2888 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
2889 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
2890 if ( 0 === strpos( $post->post_mime_type, 'audio/' ) ) {
2891 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
2892 } elseif ( 0 === strpos( $post->post_mime_type, 'video/' ) ) {
2893 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
2897 if ( $thumbnail_support ) {
2898 $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
2899 $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
2903 $hier = $post && is_post_type_hierarchical( $post->post_type );
2907 'url' => __( 'URL' ),
2908 'addMedia' => __( 'Add Media' ),
2909 'search' => __( 'Search' ),
2910 'select' => __( 'Select' ),
2911 'cancel' => __( 'Cancel' ),
2912 'update' => __( 'Update' ),
2913 'replace' => __( 'Replace' ),
2914 'remove' => __( 'Remove' ),
2915 'back' => __( 'Back' ),
2916 /* translators: This is a would-be plural string used in the media manager.
2917 If there is not a word you can use in your language to avoid issues with the
2918 lack of plural support here, turn it into "selected: %d" then translate it.
2920 'selected' => __( '%d selected' ),
2921 'dragInfo' => __( 'Drag and drop to reorder images.' ),
2924 'uploadFilesTitle' => __( 'Upload Files' ),
2925 'uploadImagesTitle' => __( 'Upload Images' ),
2928 'mediaLibraryTitle' => __( 'Media Library' ),
2929 'insertMediaTitle' => __( 'Insert Media' ),
2930 'createNewGallery' => __( 'Create a new gallery' ),
2931 'createNewPlaylist' => __( 'Create a new playlist' ),
2932 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
2933 'returnToLibrary' => __( '← Return to library' ),
2934 'allMediaItems' => __( 'All media items' ),
2935 'allDates' => __( 'All dates' ),
2936 'noItemsFound' => __( 'No items found.' ),
2937 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
2938 'unattached' => __( 'Unattached' ),
2939 'trash' => _x( 'Trash', 'noun' ),
2940 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
2941 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
2942 'warnBulkDelete' => __( "You are about to permanently delete these items.\n 'Cancel' to stop, 'OK' to delete." ),
2943 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
2944 'bulkSelect' => __( 'Bulk Select' ),
2945 'cancelSelection' => __( 'Cancel Selection' ),
2946 'trashSelected' => __( 'Trash Selected' ),
2947 'untrashSelected' => __( 'Untrash Selected' ),
2948 'deleteSelected' => __( 'Delete Selected' ),
2949 'deletePermanently' => __( 'Delete Permanently' ),
2950 'apply' => __( 'Apply' ),
2951 'filterByDate' => __( 'Filter by date' ),
2952 'filterByType' => __( 'Filter by type' ),
2953 'searchMediaLabel' => __( 'Search Media' ),
2954 'noMedia' => __( 'No media attachments found.' ),
2957 'attachmentDetails' => __( 'Attachment Details' ),
2960 'insertFromUrlTitle' => __( 'Insert from URL' ),
2963 'setFeaturedImageTitle' => __( 'Set Featured Image' ),
2964 'setFeaturedImage' => __( 'Set featured image' ),
2967 'createGalleryTitle' => __( 'Create Gallery' ),
2968 'editGalleryTitle' => __( 'Edit Gallery' ),
2969 'cancelGalleryTitle' => __( '← Cancel Gallery' ),
2970 'insertGallery' => __( 'Insert gallery' ),
2971 'updateGallery' => __( 'Update gallery' ),
2972 'addToGallery' => __( 'Add to gallery' ),
2973 'addToGalleryTitle' => __( 'Add to Gallery' ),
2974 'reverseOrder' => __( 'Reverse order' ),
2977 'imageDetailsTitle' => __( 'Image Details' ),
2978 'imageReplaceTitle' => __( 'Replace Image' ),
2979 'imageDetailsCancel' => __( 'Cancel Edit' ),
2980 'editImage' => __( 'Edit Image' ),
2983 'chooseImage' => __( 'Choose Image' ),
2984 'selectAndCrop' => __( 'Select and Crop' ),
2985 'skipCropping' => __( 'Skip Cropping' ),
2986 'cropImage' => __( 'Crop Image' ),
2987 'cropYourImage' => __( 'Crop your image' ),
2988 'cropping' => __( 'Cropping…' ),
2989 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
2990 'cropError' => __( 'There has been an error cropping your image.' ),
2993 'audioDetailsTitle' => __( 'Audio Details' ),
2994 'audioReplaceTitle' => __( 'Replace Audio' ),
2995 'audioAddSourceTitle' => __( 'Add Audio Source' ),
2996 'audioDetailsCancel' => __( 'Cancel Edit' ),
2999 'videoDetailsTitle' => __( 'Video Details' ),
3000 'videoReplaceTitle' => __( 'Replace Video' ),
3001 'videoAddSourceTitle' => __( 'Add Video Source' ),
3002 'videoDetailsCancel' => __( 'Cancel Edit' ),
3003 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
3004 'videoAddTrackTitle' => __( 'Add Subtitles' ),
3007 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
3008 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
3009 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
3010 'cancelPlaylistTitle' => __( '← Cancel Audio Playlist' ),
3011 'insertPlaylist' => __( 'Insert audio playlist' ),
3012 'updatePlaylist' => __( 'Update audio playlist' ),
3013 'addToPlaylist' => __( 'Add to audio playlist' ),
3014 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
3017 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
3018 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
3019 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
3020 'cancelVideoPlaylistTitle' => __( '← Cancel Video Playlist' ),
3021 'insertVideoPlaylist' => __( 'Insert video playlist' ),
3022 'updateVideoPlaylist' => __( 'Update video playlist' ),
3023 'addToVideoPlaylist' => __( 'Add to video playlist' ),
3024 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
3028 * Filter the media view settings.
3032 * @param array $settings List of media view settings.
3033 * @param WP_Post $post Post object.
3035 $settings = apply_filters( 'media_view_settings', $settings, $post );
3038 * Filter the media view strings.
3042 * @param array $strings List of media view strings.
3043 * @param WP_Post $post Post object.
3045 $strings = apply_filters( 'media_view_strings', $strings, $post );
3047 $strings['settings'] = $settings;
3049 // Ensure we enqueue media-editor first, that way media-views is
3050 // registered internally before we try to localize it. see #24724.
3051 wp_enqueue_script( 'media-editor' );
3052 wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
3054 wp_enqueue_script( 'media-audiovideo' );
3055 wp_enqueue_style( 'media-views' );
3057 wp_enqueue_script( 'mce-view' );
3058 wp_enqueue_script( 'image-edit' );
3060 wp_enqueue_style( 'imgareaselect' );
3061 wp_plupload_default_settings();
3063 require_once ABSPATH . WPINC . '/media-template.php';
3064 add_action( 'admin_footer', 'wp_print_media_templates' );
3065 add_action( 'wp_footer', 'wp_print_media_templates' );
3066 add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
3069 * Fires at the conclusion of wp_enqueue_media().
3073 do_action( 'wp_enqueue_media' );
3077 * Retrieve media attached to the passed post.
3081 * @param string $type Mime type.
3082 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3083 * @return array Found attachments.
3085 function get_attached_media( $type, $post = 0 ) {
3086 if ( ! $post = get_post( $post ) )
3090 'post_parent' => $post->ID,
3091 'post_type' => 'attachment',
3092 'post_mime_type' => $type,
3093 'posts_per_page' => -1,
3094 'orderby' => 'menu_order',
3099 * Filter arguments used to retrieve media attached to the given post.
3103 * @param array $args Post query arguments.
3104 * @param string $type Mime type of the desired media.
3105 * @param mixed $post Post ID or object.
3107 $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
3109 $children = get_children( $args );
3112 * Filter the list of media attached to the given post.
3116 * @param array $children Associative array of media attached to the given post.
3117 * @param string $type Mime type of the media desired.
3118 * @param mixed $post Post ID or object.
3120 return (array) apply_filters( 'get_attached_media', $children, $type, $post );
3124 * Check the content blob for an audio, video, object, embed, or iframe tags.
3128 * @param string $content A string which might contain media data.
3129 * @param array $types array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'
3130 * @return array A list of found HTML media embeds
3132 function get_media_embedded_in_content( $content, $types = null ) {
3134 $allowed_media_types = array( 'audio', 'video', 'object', 'embed', 'iframe' );
3135 if ( ! empty( $types ) ) {
3136 if ( ! is_array( $types ) )
3137 $types = array( $types );
3138 $allowed_media_types = array_intersect( $allowed_media_types, $types );
3141 foreach ( $allowed_media_types as $tag ) {
3142 if ( preg_match( '#' . get_tag_regex( $tag ) . '#', $content, $matches ) ) {
3143 $html[] = $matches[0];
3151 * Retrieve galleries from the passed post's content.
3155 * @param int|WP_Post $post Optional. Post ID or object.
3156 * @param bool $html Whether to return HTML or data in the array.
3157 * @return array A list of arrays, each containing gallery data and srcs parsed
3158 * from the expanded shortcode.
3160 function get_post_galleries( $post, $html = true ) {
3161 if ( ! $post = get_post( $post ) )
3164 if ( ! has_shortcode( $post->post_content, 'gallery' ) )
3167 $galleries = array();
3168 if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
3169 foreach ( $matches as $shortcode ) {
3170 if ( 'gallery' === $shortcode[2] ) {
3173 $gallery = do_shortcode_tag( $shortcode );
3175 $galleries[] = $gallery;
3177 preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
3178 if ( ! empty( $src ) ) {
3179 foreach ( $src as $s )
3183 $data = shortcode_parse_atts( $shortcode[3] );
3184 $data['src'] = array_values( array_unique( $srcs ) );
3185 $galleries[] = $data;
3192 * Filter the list of all found galleries in the given post.
3196 * @param array $galleries Associative array of all found post galleries.
3197 * @param WP_Post $post Post object.
3199 return apply_filters( 'get_post_galleries', $galleries, $post );
3203 * Check a specified post's content for gallery and, if present, return the first
3207 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3208 * @param bool $html Whether to return HTML or data.
3209 * @return string|array Gallery data and srcs parsed from the expanded shortcode.
3211 function get_post_gallery( $post = 0, $html = true ) {
3212 $galleries = get_post_galleries( $post, $html );
3213 $gallery = reset( $galleries );
3216 * Filter the first-found post gallery.
3220 * @param array $gallery The first-found post gallery.
3221 * @param int|WP_Post $post Post ID or object.
3222 * @param array $galleries Associative array of all found post galleries.
3224 return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
3228 * Retrieve the image srcs from galleries from a post's content, if present
3232 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3233 * @return array A list of lists, each containing image srcs parsed.
3234 * from an expanded shortcode
3236 function get_post_galleries_images( $post = 0 ) {
3237 $galleries = get_post_galleries( $post, false );
3238 return wp_list_pluck( $galleries, 'src' );
3242 * Check a post's content for galleries and return the image srcs for the first found gallery
3246 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3247 * @return array A list of a gallery's image srcs in order.
3249 function get_post_gallery_images( $post = 0 ) {
3250 $gallery = get_post_gallery( $post, false );
3251 return empty( $gallery['src'] ) ? array() : $gallery['src'];
3255 * Maybe attempt to generate attachment metadata, if missing.
3259 * @param WP_Post $attachment Attachment object.
3261 function wp_maybe_generate_attachment_metadata( $attachment ) {
3262 if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
3266 $file = get_attached_file( $attachment_id );
3267 $meta = wp_get_attachment_metadata( $attachment_id );
3268 if ( empty( $meta ) && file_exists( $file ) ) {
3269 $_meta = get_post_meta( $attachment_id );
3270 $regeneration_lock = 'wp_generating_att_' . $attachment_id;
3271 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
3272 set_transient( $regeneration_lock, $file );
3273 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
3274 delete_transient( $regeneration_lock );
3280 * Try to convert an attachment URL into a post ID.
3284 * @global wpdb $wpdb WordPress database abstraction object.
3286 * @param string $url The URL to resolve.
3287 * @return int The found post ID.
3289 function attachment_url_to_postid( $url ) {
3292 $dir = wp_upload_dir();
3295 if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
3296 $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
3299 $sql = $wpdb->prepare(
3300 "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
3303 $post_id = $wpdb->get_var( $sql );
3304 if ( ! empty( $post_id ) ) {
3305 return (int) $post_id;
3310 * Return the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
3314 * @global $wp_version
3316 * @return array The relevant CSS file URLs.
3318 function wpview_media_sandbox_styles() {
3319 $version = 'ver=' . $GLOBALS['wp_version'];
3320 $mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
3321 $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
3323 return array( $mediaelement, $wpmediaelement );