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 * @global int $content_width
30 * @global array $_wp_additional_image_sizes
32 * @param int $width Width of the image in pixels.
33 * @param int $height Height of the image in pixels.
34 * @param string|array $size Optional. Size or array of sizes of what the result image
35 * should be. Accepts any valid image size name. Default 'medium'.
36 * @param string $context Optional. Could be 'display' (like in a theme) or 'edit'
37 * (like inserting into an editor). Default null.
38 * @return array Width and height of what the result image should resize to.
40 function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
41 global $content_width, $_wp_additional_image_sizes;
44 $context = is_admin() ? 'edit' : 'display';
46 if ( is_array($size) ) {
47 $max_width = $size[0];
48 $max_height = $size[1];
50 elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
51 $max_width = intval(get_option('thumbnail_size_w'));
52 $max_height = intval(get_option('thumbnail_size_h'));
53 // last chance thumbnail size defaults
54 if ( !$max_width && !$max_height ) {
59 elseif ( $size == 'medium' ) {
60 $max_width = intval(get_option('medium_size_w'));
61 $max_height = intval(get_option('medium_size_h'));
62 // if no width is set, default to the theme content width if available
64 elseif ( $size == 'large' ) {
66 * We're inserting a large size image into the editor. If it's a really
67 * big image we'll scale it down to fit reasonably within the editor
68 * itself, and within the theme's content width if it's known. The user
69 * can resize it in the editor if they wish.
71 $max_width = intval(get_option('large_size_w'));
72 $max_height = intval(get_option('large_size_h'));
73 if ( intval($content_width) > 0 )
74 $max_width = min( intval($content_width), $max_width );
75 } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
76 $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
77 $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
78 if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
79 $max_width = min( intval($content_width), $max_width );
81 // $size == 'full' has no constraint
84 $max_height = $height;
88 * Filter the maximum image size dimensions for the editor.
92 * @param array $max_image_size An array with the width as the first element,
93 * and the height as the second element.
94 * @param string|array $size Size of what the result image should be.
95 * @param string $context The context the image is being resized for.
96 * Possible values are 'display' (like in a theme)
97 * or 'edit' (like inserting into an editor).
99 list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
101 return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
105 * Retrieve width and height attributes using given width and height values.
107 * Both attributes are required in the sense that both parameters must have a
108 * value, but are optional in that if you set them to false or null, then they
109 * will not be added to the returned string.
111 * You can set the value using a string, but it will only take numeric values.
112 * If you wish to put 'px' after the numbers, then it will be stripped out of
117 * @param int|string $width Image width in pixels.
118 * @param int|string $height Image height in pixels.
119 * @return string HTML attributes for width and, or height.
121 function image_hwstring( $width, $height ) {
124 $out .= 'width="'.intval($width).'" ';
126 $out .= 'height="'.intval($height).'" ';
131 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
133 * Array with image url, width, height, and whether is intermediate size, in
134 * that order is returned on success is returned. $is_intermediate is true if
135 * $url is a resized image, false if it is the original.
137 * The URL might be the original image, or it might be a resized version. This
138 * function won't create a new resized copy, it will just return an already
139 * resized one if it exists.
141 * A plugin may use the 'image_downsize' filter to hook into and offer image
142 * resizing services for images. The hook must return an array with the same
143 * elements that are returned in the function. The first element being the URL
144 * to the new image that was resized.
148 * @param int $id Attachment ID for image.
149 * @param array|string $size Optional. Image size to scale to. Accepts a registered image size
150 * or flat array of height and width values. Default 'medium'.
151 * @return false|array False on failure, array on success.
153 function image_downsize( $id, $size = 'medium' ) {
155 if ( !wp_attachment_is_image($id) )
159 * Filter whether to preempt the output of image_downsize().
161 * Passing a truthy value to the filter will effectively short-circuit
162 * down-sizing the image, returning that value as output instead.
166 * @param bool $downsize Whether to short-circuit the image downsize. Default false.
167 * @param int $id Attachment ID for image.
168 * @param array|string $size Size of image, either array or string. Default 'medium'.
170 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
174 $img_url = wp_get_attachment_url($id);
175 $meta = wp_get_attachment_metadata($id);
176 $width = $height = 0;
177 $is_intermediate = false;
178 $img_url_basename = wp_basename($img_url);
180 // try for a new style intermediate size
181 if ( $intermediate = image_get_intermediate_size($id, $size) ) {
182 $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
183 $width = $intermediate['width'];
184 $height = $intermediate['height'];
185 $is_intermediate = true;
187 elseif ( $size == 'thumbnail' ) {
188 // fall back to the old thumbnail
189 if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
190 $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
193 $is_intermediate = true;
196 if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
197 // any other type: use the real image
198 $width = $meta['width'];
199 $height = $meta['height'];
203 // we have the actual image size, but might need to further constrain it if content_width is narrower
204 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
206 return array( $img_url, $width, $height, $is_intermediate );
213 * Register a new image size.
215 * Cropping behavior for the image size is dependent on the value of $crop:
216 * 1. If false (default), images will be scaled, not cropped.
217 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
218 * - x_crop_position accepts 'left' 'center', or 'right'.
219 * - y_crop_position accepts 'top', 'center', or 'bottom'.
220 * Images will be cropped to the specified dimensions within the defined crop area.
221 * 3. If true, images will be cropped to the specified dimensions using center positions.
225 * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
227 * @param string $name Image size identifier.
228 * @param int $width Image width in pixels.
229 * @param int $height Image height in pixels.
230 * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
231 * An array can specify positioning of the crop area. Default false.
233 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
234 global $_wp_additional_image_sizes;
236 $_wp_additional_image_sizes[ $name ] = array(
237 'width' => absint( $width ),
238 'height' => absint( $height ),
244 * Check if an image size exists.
248 * @global array $_wp_additional_image_sizes
250 * @param string $name The image size to check.
251 * @return bool True if the image size exists, false if not.
253 function has_image_size( $name ) {
254 global $_wp_additional_image_sizes;
256 return isset( $_wp_additional_image_sizes[ $name ] );
260 * Remove a new image size.
264 * @global array $_wp_additional_image_sizes
266 * @param string $name The image size to remove.
267 * @return bool True if the image size was successfully removed, false on failure.
269 function remove_image_size( $name ) {
270 global $_wp_additional_image_sizes;
272 if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
273 unset( $_wp_additional_image_sizes[ $name ] );
281 * Registers an image size for the post thumbnail.
285 * @see add_image_size() for details on cropping behavior.
287 * @param int $width Image width in pixels.
288 * @param int $height Image height in pixels.
289 * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
290 * An array can specify positioning of the crop area. Default false.
292 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
293 add_image_size( 'post-thumbnail', $width, $height, $crop );
297 * Gets an img tag for an image attachment, scaling it down if requested.
299 * The filter 'get_image_tag_class' allows for changing the class name for the
300 * image without having to use regular expressions on the HTML content. The
301 * parameters are: what WordPress will use for the class, the Attachment ID,
302 * image align value, and the size the image should be.
304 * The second filter 'get_image_tag' has the HTML content, which can then be
305 * further manipulated by a plugin to change all attribute values and even HTML
310 * @param int $id Attachment ID.
311 * @param string $alt Image Description for the alt attribute.
312 * @param string $title Image Description for the title attribute.
313 * @param string $align Part of the class name for aligning the image.
314 * @param string|array $size Optional. Registered image size to retrieve a tag for, or flat array
315 * of height and width values. Default 'medium'.
316 * @return string HTML IMG element for given image attachment
318 function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
320 list( $img_src, $width, $height ) = image_downsize($id, $size);
321 $hwstring = image_hwstring($width, $height);
323 $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
325 $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
328 * Filter the value of the attachment's image tag class attribute.
332 * @param string $class CSS class name or space-separated list of classes.
333 * @param int $id Attachment ID.
334 * @param string $align Part of the class name for aligning the image.
335 * @param string $size Optional. Default is 'medium'.
337 $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
339 $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
342 * Filter the HTML content for the image tag.
346 * @param string $html HTML content for the image.
347 * @param int $id Attachment ID.
348 * @param string $alt Alternate text.
349 * @param string $title Attachment title.
350 * @param string $align Part of the class name for aligning the image.
351 * @param string $size Optional. Default is 'medium'.
353 return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
357 * Calculates the new dimensions for a down-sampled image.
359 * If either width or height are empty, no constraint is applied on
364 * @param int $current_width Current width of the image.
365 * @param int $current_height Current height of the image.
366 * @param int $max_width Optional. Max width in pixels to constrain to. Default 0.
367 * @param int $max_height Optional. Max height in pixels to constrain to. Default 0.
368 * @return array First item is the width, the second item is the height.
370 function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
371 if ( !$max_width && !$max_height )
372 return array( $current_width, $current_height );
374 $width_ratio = $height_ratio = 1.0;
375 $did_width = $did_height = false;
377 if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
378 $width_ratio = $max_width / $current_width;
382 if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
383 $height_ratio = $max_height / $current_height;
387 // Calculate the larger/smaller ratios
388 $smaller_ratio = min( $width_ratio, $height_ratio );
389 $larger_ratio = max( $width_ratio, $height_ratio );
391 if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
392 // The larger ratio is too big. It would result in an overflow.
393 $ratio = $smaller_ratio;
395 // The larger ratio fits, and is likely to be a more "snug" fit.
396 $ratio = $larger_ratio;
399 // Very small dimensions may result in 0, 1 should be the minimum.
400 $w = max ( 1, (int) round( $current_width * $ratio ) );
401 $h = max ( 1, (int) round( $current_height * $ratio ) );
403 // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
404 // 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.
405 // Thus we look for dimensions that are one pixel shy of the max value and bump them up
407 // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
408 if ( $did_width && $w == $max_width - 1 ) {
409 $w = $max_width; // Round it up
412 // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
413 if ( $did_height && $h == $max_height - 1 ) {
414 $h = $max_height; // Round it up
418 * Filter dimensions to constrain down-sampled images to.
422 * @param array $dimensions The image width and height.
423 * @param int $current_width The current width of the image.
424 * @param int $current_height The current height of the image.
425 * @param int $max_width The maximum width permitted.
426 * @param int $max_height The maximum height permitted.
428 return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
432 * Retrieves calculated resize dimensions for use in WP_Image_Editor.
434 * Calculates dimensions and coordinates for a resized image that fits
435 * within a specified width and height.
437 * Cropping behavior is dependent on the value of $crop:
438 * 1. If false (default), images will not be cropped.
439 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
440 * - x_crop_position accepts 'left' 'center', or 'right'.
441 * - y_crop_position accepts 'top', 'center', or 'bottom'.
442 * Images will be cropped to the specified dimensions within the defined crop area.
443 * 3. If true, images will be cropped to the specified dimensions using center positions.
447 * @param int $orig_w Original width in pixels.
448 * @param int $orig_h Original height in pixels.
449 * @param int $dest_w New width in pixels.
450 * @param int $dest_h New height in pixels.
451 * @param bool|array $crop Optional. Whether to crop image to specified height and width or resize.
452 * An array can specify positioning of the crop area. Default false.
453 * @return false|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
455 function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
457 if ($orig_w <= 0 || $orig_h <= 0)
459 // at least one of dest_w or dest_h must be specific
460 if ($dest_w <= 0 && $dest_h <= 0)
464 * Filter whether to preempt calculating the image resize dimensions.
466 * Passing a non-null value to the filter will effectively short-circuit
467 * image_resize_dimensions(), returning that value instead.
471 * @param null|mixed $null Whether to preempt output of the resize dimensions.
472 * @param int $orig_w Original width in pixels.
473 * @param int $orig_h Original height in pixels.
474 * @param int $dest_w New width in pixels.
475 * @param int $dest_h New height in pixels.
476 * @param bool|array $crop Whether to crop image to specified height and width or resize.
477 * An array can specify positioning of the crop area. Default false.
479 $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
480 if ( null !== $output )
484 // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
485 $aspect_ratio = $orig_w / $orig_h;
486 $new_w = min($dest_w, $orig_w);
487 $new_h = min($dest_h, $orig_h);
490 $new_w = (int) round( $new_h * $aspect_ratio );
494 $new_h = (int) round( $new_w / $aspect_ratio );
497 $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
499 $crop_w = round($new_w / $size_ratio);
500 $crop_h = round($new_h / $size_ratio);
502 if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
503 $crop = array( 'center', 'center' );
506 list( $x, $y ) = $crop;
508 if ( 'left' === $x ) {
510 } elseif ( 'right' === $x ) {
511 $s_x = $orig_w - $crop_w;
513 $s_x = floor( ( $orig_w - $crop_w ) / 2 );
516 if ( 'top' === $y ) {
518 } elseif ( 'bottom' === $y ) {
519 $s_y = $orig_h - $crop_h;
521 $s_y = floor( ( $orig_h - $crop_h ) / 2 );
524 // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
531 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
534 // if the resulting image would be the same size or larger we don't want to resize it
535 if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
539 // the return array matches the parameters to imagecopyresampled()
540 // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
541 return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
546 * Resizes an image to make a thumbnail or intermediate size.
548 * The returned array has the file size, the image width, and image height. The
549 * filter 'image_make_intermediate_size' can be used to hook in and change the
550 * values of the returned array. The only parameter is the resized file path.
554 * @param string $file File path.
555 * @param int $width Image width.
556 * @param int $height Image height.
557 * @param bool $crop Optional. Whether to crop image to specified height and width or resize.
559 * @return false|array False, if no image was created. Metadata array on success.
561 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
562 if ( $width || $height ) {
563 $editor = wp_get_image_editor( $file );
565 if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
568 $resized_file = $editor->save();
570 if ( ! is_wp_error( $resized_file ) && $resized_file ) {
571 unset( $resized_file['path'] );
572 return $resized_file;
579 * Retrieves the image's intermediate size (resized) path, width, and height.
581 * The $size parameter can be an array with the width and height respectively.
582 * If the size matches the 'sizes' metadata array for width and height, then it
583 * will be used. If there is no direct match, then the nearest image size larger
584 * than the specified size will be used. If nothing is found, then the function
585 * will break out and return false.
587 * The metadata 'sizes' is used for compatible sizes that can be used for the
588 * parameter $size value.
590 * The url path will be given, when the $size parameter is a string.
592 * If you are passing an array for the $size, you should consider using
593 * add_image_size() so that a cropped version is generated. It's much more
594 * efficient than having to find the closest-sized image and then having the
595 * browser scale down the image.
599 * @param int $post_id Attachment ID.
600 * @param array|string $size Optional. Registered image size to retrieve or flat array of height
601 * and width dimensions. Default 'thumbnail'.
602 * @return false|array False on failure or array of file path, width, and height on success.
604 function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
605 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
608 // get the best one for a specified set of dimensions
609 if ( is_array($size) && !empty($imagedata['sizes']) ) {
612 foreach ( $imagedata['sizes'] as $_size => $data ) {
613 // already cropped to width or height; so use this size
614 if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
615 $file = $data['file'];
616 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
617 return compact( 'file', 'width', 'height' );
619 // add to lookup table: area => size
620 $areas[$data['width'] * $data['height']] = $_size;
622 if ( !$size || !empty($areas) ) {
623 // find for the smallest image not smaller than the desired size
625 foreach ( $areas as $_size ) {
626 $data = $imagedata['sizes'][$_size];
627 if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
628 // Skip images with unexpectedly divergent aspect ratios (crops)
629 // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
630 $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
631 // 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
632 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'] ) ) )
634 // If we're still here, then we're going to use this size
635 $file = $data['file'];
636 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
637 return compact( 'file', 'width', 'height' );
643 if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
646 $data = $imagedata['sizes'][$size];
647 // include the full filesystem path of the intermediate file
648 if ( empty($data['path']) && !empty($data['file']) ) {
649 $file_url = wp_get_attachment_url($post_id);
650 $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
651 $data['url'] = path_join( dirname($file_url), $data['file'] );
657 * Gets the available intermediate image sizes.
661 * @global array $_wp_additional_image_sizes
663 * @return array Returns a filtered array of image size strings.
665 function get_intermediate_image_sizes() {
666 global $_wp_additional_image_sizes;
667 $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
668 if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
669 $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
672 * Filter the list of intermediate image sizes.
676 * @param array $image_sizes An array of intermediate image sizes. Defaults
677 * are 'thumbnail', 'medium', 'large'.
679 return apply_filters( 'intermediate_image_sizes', $image_sizes );
683 * Retrieve an image to represent an attachment.
685 * A mime icon for files, thumbnail or intermediate size for images.
689 * @param int $attachment_id Image attachment ID.
690 * @param string|array $size Optional. Registered image size to retrieve the source for or a flat
691 * array of height and width dimensions. Default 'thumbnail'.
692 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
693 * @return false|array Returns an array (url, width, height), or false, if no image is available.
695 function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
696 // get a thumbnail or intermediate image if there is one
697 $image = image_downsize( $attachment_id, $size );
701 if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {
702 /** This filter is documented in wp-includes/post.php */
703 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
705 $src_file = $icon_dir . '/' . wp_basename( $src );
706 @list( $width, $height ) = getimagesize( $src_file );
709 if ( $src && $width && $height ) {
710 $image = array( $src, $width, $height );
714 * Filter the image src result.
718 * @param array|false $image Either array with src, width & height, icon src, or false.
719 * @param int $attachment_id Image attachment ID.
720 * @param string|array $size Registered image size to retrieve the source for or a flat
721 * array of height and width dimensions. Default 'thumbnail'.
722 * @param bool $icon Whether the image should be treated as an icon. Default false.
724 return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
728 * Get an HTML img element representing an image attachment
730 * While `$size` will accept an array, it is better to register a size with
731 * add_image_size() so that a cropped version is generated. It's much more
732 * efficient than having to find the closest-sized image and then having the
733 * browser scale down the image.
737 * @param int $attachment_id Image attachment ID.
738 * @param string|array $size Optional. Registered image size or flat array of height and width
739 * dimensions. Default 'thumbnail'.
740 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
741 * @param string|array $attr Optional. Attributes for the image markup. Default empty.
742 * @return string HTML img element or empty string on failure.
744 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
746 $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
748 list($src, $width, $height) = $image;
749 $hwstring = image_hwstring($width, $height);
751 if ( is_array( $size_class ) ) {
752 $size_class = join( 'x', $size_class );
754 $attachment = get_post($attachment_id);
755 $default_attr = array(
757 'class' => "attachment-$size_class",
758 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
760 if ( empty($default_attr['alt']) )
761 $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
762 if ( empty($default_attr['alt']) )
763 $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
765 $attr = wp_parse_args($attr, $default_attr);
768 * Filter the list of attachment image attributes.
772 * @param array $attr Attributes for the image markup.
773 * @param WP_Post $attachment Image attachment post.
774 * @param string|array $size Requested size.
776 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
777 $attr = array_map( 'esc_attr', $attr );
778 $html = rtrim("<img $hwstring");
779 foreach ( $attr as $name => $value ) {
780 $html .= " $name=" . '"' . $value . '"';
789 * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
791 * Uses the 'begin_fetch_post_thumbnail_html' and 'end_fetch_post_thumbnail_html' action hooks to
792 * dynamically add/remove itself so as to only filter post thumbnails.
797 * @param array $attr Thumbnail attributes including src, class, alt, title.
798 * @return array Modified array of attributes including the new 'wp-post-image' class.
800 function _wp_post_thumbnail_class_filter( $attr ) {
801 $attr['class'] .= ' wp-post-image';
806 * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
807 * filter hook. Internal use only.
812 * @param array $attr Thumbnail attributes including src, class, alt, title.
814 function _wp_post_thumbnail_class_filter_add( $attr ) {
815 add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
819 * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
820 * filter hook. Internal use only.
825 * @param array $attr Thumbnail attributes including src, class, alt, title.
827 function _wp_post_thumbnail_class_filter_remove( $attr ) {
828 remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
831 add_shortcode('wp_caption', 'img_caption_shortcode');
832 add_shortcode('caption', 'img_caption_shortcode');
835 * Builds the Caption shortcode output.
837 * Allows a plugin to replace the content that would otherwise be returned. The
838 * filter is 'img_caption_shortcode' and passes an empty string, the attr
839 * parameter and the content parameter values.
841 * The supported attributes for the shortcode are 'id', 'align', 'width', and
846 * @param array $attr {
847 * Attributes of the caption shortcode.
849 * @type string $id ID of the div element for the caption.
850 * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
851 * 'aligncenter', alignright', 'alignnone'.
852 * @type int $width The width of the caption, in pixels.
853 * @type string $caption The caption text.
854 * @type string $class Additional class name(s) added to the caption container.
856 * @param string $content Shortcode content.
857 * @return string HTML content to display the caption.
859 function img_caption_shortcode( $attr, $content = null ) {
860 // New-style shortcode with the caption inside the shortcode with the link and image tags.
861 if ( ! isset( $attr['caption'] ) ) {
862 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
863 $content = $matches[1];
864 $attr['caption'] = trim( $matches[2] );
866 } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
867 $attr['caption'] = wp_kses( $attr['caption'], 'post' );
871 * Filter the default caption shortcode output.
873 * If the filtered output isn't empty, it will be used instead of generating
874 * the default caption template.
878 * @see img_caption_shortcode()
880 * @param string $output The caption output. Default empty.
881 * @param array $attr Attributes of the caption shortcode.
882 * @param string $content The image element, possibly wrapped in a hyperlink.
884 $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
888 $atts = shortcode_atts( array(
890 'align' => 'alignnone',
894 ), $attr, 'caption' );
896 $atts['width'] = (int) $atts['width'];
897 if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
900 if ( ! empty( $atts['id'] ) )
901 $atts['id'] = 'id="' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '" ';
903 $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
905 if ( current_theme_supports( 'html5', 'caption' ) ) {
906 return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
907 . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
910 $caption_width = 10 + $atts['width'];
913 * Filter the width of an image's caption.
915 * By default, the caption is 10 pixels greater than the width of the image,
916 * to prevent post content from running up against a floated image.
920 * @see img_caption_shortcode()
922 * @param int $caption_width Width of the caption in pixels. To remove this inline style,
924 * @param array $atts Attributes of the caption shortcode.
925 * @param string $content The image element, possibly wrapped in a hyperlink.
927 $caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
930 if ( $caption_width )
931 $style = 'style="width: ' . (int) $caption_width . 'px" ';
933 return '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
934 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
937 add_shortcode('gallery', 'gallery_shortcode');
940 * Builds the Gallery shortcode output.
942 * This implements the functionality of the Gallery Shortcode for displaying
943 * WordPress images on a post.
947 * @staticvar int $instance
949 * @param array $attr {
950 * Attributes of the gallery shortcode.
952 * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
953 * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
954 * Accepts any valid SQL ORDERBY statement.
955 * @type int $id Post ID.
956 * @type string $itemtag HTML tag to use for each image in the gallery.
957 * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
958 * @type string $icontag HTML tag to use for each image's icon.
959 * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
960 * @type string $captiontag HTML tag to use for each image's caption.
961 * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
962 * @type int $columns Number of columns of images to display. Default 3.
963 * @type string $size Size of the images to display. Default 'thumbnail'.
964 * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
965 * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
966 * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
967 * @type string $link What to link each image to. Default empty (links to the attachment page).
968 * Accepts 'file', 'none'.
970 * @return string HTML content to display gallery.
972 function gallery_shortcode( $attr ) {
975 static $instance = 0;
978 if ( ! empty( $attr['ids'] ) ) {
979 // 'ids' is explicitly ordered, unless you specify otherwise.
980 if ( empty( $attr['orderby'] ) ) {
981 $attr['orderby'] = 'post__in';
983 $attr['include'] = $attr['ids'];
987 * Filter the default gallery shortcode output.
989 * If the filtered output isn't empty, it will be used instead of generating
990 * the default gallery template.
993 * @since 4.2.0 The `$instance` parameter was added.
995 * @see gallery_shortcode()
997 * @param string $output The gallery output. Default empty.
998 * @param array $attr Attributes of the gallery shortcode.
999 * @param int $instance Unique numeric ID of this gallery shortcode instance.
1001 $output = apply_filters( 'post_gallery', '', $attr, $instance );
1002 if ( $output != '' ) {
1006 $html5 = current_theme_supports( 'html5', 'gallery' );
1007 $atts = shortcode_atts( array(
1009 'orderby' => 'menu_order ID',
1010 'id' => $post ? $post->ID : 0,
1011 'itemtag' => $html5 ? 'figure' : 'dl',
1012 'icontag' => $html5 ? 'div' : 'dt',
1013 'captiontag' => $html5 ? 'figcaption' : 'dd',
1015 'size' => 'thumbnail',
1019 ), $attr, 'gallery' );
1021 $id = intval( $atts['id'] );
1023 if ( ! empty( $atts['include'] ) ) {
1024 $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1026 $attachments = array();
1027 foreach ( $_attachments as $key => $val ) {
1028 $attachments[$val->ID] = $_attachments[$key];
1030 } elseif ( ! empty( $atts['exclude'] ) ) {
1031 $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'] ) );
1033 $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1036 if ( empty( $attachments ) ) {
1042 foreach ( $attachments as $att_id => $attachment ) {
1043 $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
1048 $itemtag = tag_escape( $atts['itemtag'] );
1049 $captiontag = tag_escape( $atts['captiontag'] );
1050 $icontag = tag_escape( $atts['icontag'] );
1051 $valid_tags = wp_kses_allowed_html( 'post' );
1052 if ( ! isset( $valid_tags[ $itemtag ] ) ) {
1055 if ( ! isset( $valid_tags[ $captiontag ] ) ) {
1058 if ( ! isset( $valid_tags[ $icontag ] ) ) {
1062 $columns = intval( $atts['columns'] );
1063 $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
1064 $float = is_rtl() ? 'right' : 'left';
1066 $selector = "gallery-{$instance}";
1068 $gallery_style = '';
1071 * Filter whether to print default gallery styles.
1075 * @param bool $print Whether to print default gallery styles.
1076 * Defaults to false if the theme supports HTML5 galleries.
1077 * Otherwise, defaults to true.
1079 if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1081 <style type='text/css'>
1085 #{$selector} .gallery-item {
1089 width: {$itemwidth}%;
1092 border: 2px solid #cfcfcf;
1094 #{$selector} .gallery-caption {
1097 /* see gallery_shortcode() in wp-includes/media.php */
1101 $size_class = sanitize_html_class( $atts['size'] );
1102 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1105 * Filter the default gallery shortcode CSS styles.
1109 * @param string $gallery_style Default CSS styles and opening HTML div container
1110 * for the gallery shortcode output.
1112 $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1115 foreach ( $attachments as $id => $attachment ) {
1117 $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
1118 if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
1119 $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
1120 } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
1121 $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
1123 $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
1125 $image_meta = wp_get_attachment_metadata( $id );
1128 if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
1129 $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1131 $output .= "<{$itemtag} class='gallery-item'>";
1133 <{$icontag} class='gallery-icon {$orientation}'>
1136 if ( $captiontag && trim($attachment->post_excerpt) ) {
1138 <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
1139 " . wptexturize($attachment->post_excerpt) . "
1142 $output .= "</{$itemtag}>";
1143 if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1144 $output .= '<br style="clear: both" />';
1148 if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1150 <br style='clear: both' />";
1160 * Outputs the templates used by playlists.
1164 function wp_underscore_playlist_templates() {
1166 <script type="text/html" id="tmpl-wp-playlist-current-item">
1167 <# if ( data.image ) { #>
1168 <img src="{{ data.thumb.src }}"/>
1170 <div class="wp-playlist-caption">
1171 <span class="wp-playlist-item-meta wp-playlist-item-title">“{{ data.title }}”</span>
1172 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1173 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1176 <script type="text/html" id="tmpl-wp-playlist-item">
1177 <div class="wp-playlist-item">
1178 <a class="wp-playlist-caption" href="{{ data.src }}">
1179 {{ data.index ? ( data.index + '. ' ) : '' }}
1180 <# if ( data.caption ) { #>
1183 <span class="wp-playlist-item-title">“{{{ data.title }}}”</span>
1184 <# if ( data.artists && data.meta.artist ) { #>
1185 <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span>
1189 <# if ( data.meta.length_formatted ) { #>
1190 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1198 * Outputs and enqueue default scripts and styles for playlists.
1202 * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1204 function wp_playlist_scripts( $type ) {
1205 wp_enqueue_style( 'wp-mediaelement' );
1206 wp_enqueue_script( 'wp-playlist' );
1208 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1210 add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1211 add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1215 * Builds the Playlist shortcode output.
1217 * This implements the functionality of the playlist shortcode for displaying
1218 * a collection of WordPress audio or video files in a post.
1222 * @global int $content_width
1223 * @staticvar int $instance
1225 * @param array $attr {
1226 * Array of default playlist attributes.
1228 * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
1229 * @type string $order Designates ascending or descending order of items in the playlist.
1230 * Accepts 'ASC', 'DESC'. Default 'ASC'.
1231 * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
1232 * passed, this defaults to the order of the $ids array ('post__in').
1233 * Otherwise default is 'menu_order ID'.
1234 * @type int $id If an explicit $ids array is not present, this parameter
1235 * will determine which attachments are used for the playlist.
1236 * Default is the current post ID.
1237 * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
1238 * a playlist will be created from all $type attachments of $id.
1240 * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
1241 * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
1242 * @type bool $tracklist Whether to show or hide the playlist. Default true.
1243 * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
1244 * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
1245 * thumbnail). Default true.
1246 * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
1249 * @return string Playlist output. Empty string if the passed type is unsupported.
1251 function wp_playlist_shortcode( $attr ) {
1252 global $content_width;
1255 static $instance = 0;
1258 if ( ! empty( $attr['ids'] ) ) {
1259 // 'ids' is explicitly ordered, unless you specify otherwise.
1260 if ( empty( $attr['orderby'] ) ) {
1261 $attr['orderby'] = 'post__in';
1263 $attr['include'] = $attr['ids'];
1267 * Filter the playlist output.
1269 * Passing a non-empty value to the filter will short-circuit generation
1270 * of the default playlist output, returning the passed value instead.
1273 * @since 4.2.0 The `$instance` parameter was added.
1275 * @param string $output Playlist output. Default empty.
1276 * @param array $attr An array of shortcode attributes.
1277 * @param int $instance Unique numeric ID of this playlist shortcode instance.
1279 $output = apply_filters( 'post_playlist', '', $attr, $instance );
1280 if ( $output != '' ) {
1284 $atts = shortcode_atts( array(
1287 'orderby' => 'menu_order ID',
1288 'id' => $post ? $post->ID : 0,
1292 'tracklist' => true,
1293 'tracknumbers' => true,
1296 ), $attr, 'playlist' );
1298 $id = intval( $atts['id'] );
1300 if ( $atts['type'] !== 'audio' ) {
1301 $atts['type'] = 'video';
1305 'post_status' => 'inherit',
1306 'post_type' => 'attachment',
1307 'post_mime_type' => $atts['type'],
1308 'order' => $atts['order'],
1309 'orderby' => $atts['orderby']
1312 if ( ! empty( $atts['include'] ) ) {
1313 $args['include'] = $atts['include'];
1314 $_attachments = get_posts( $args );
1316 $attachments = array();
1317 foreach ( $_attachments as $key => $val ) {
1318 $attachments[$val->ID] = $_attachments[$key];
1320 } elseif ( ! empty( $atts['exclude'] ) ) {
1321 $args['post_parent'] = $id;
1322 $args['exclude'] = $atts['exclude'];
1323 $attachments = get_children( $args );
1325 $args['post_parent'] = $id;
1326 $attachments = get_children( $args );
1329 if ( empty( $attachments ) ) {
1335 foreach ( $attachments as $att_id => $attachment ) {
1336 $output .= wp_get_attachment_link( $att_id ) . "\n";
1341 $outer = 22; // default padding and border of wrapper
1343 $default_width = 640;
1344 $default_height = 360;
1346 $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
1347 $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
1350 'type' => $atts['type'],
1351 // don't pass strings to JSON, will be truthy in JS
1352 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
1353 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
1354 'images' => wp_validate_boolean( $atts['images'] ),
1355 'artists' => wp_validate_boolean( $atts['artists'] ),
1359 foreach ( $attachments as $attachment ) {
1360 $url = wp_get_attachment_url( $attachment->ID );
1361 $ftype = wp_check_filetype( $url, wp_get_mime_types() );
1364 'type' => $ftype['type'],
1365 'title' => $attachment->post_title,
1366 'caption' => $attachment->post_excerpt,
1367 'description' => $attachment->post_content
1370 $track['meta'] = array();
1371 $meta = wp_get_attachment_metadata( $attachment->ID );
1372 if ( ! empty( $meta ) ) {
1374 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
1375 if ( ! empty( $meta[ $key ] ) ) {
1376 $track['meta'][ $key ] = $meta[ $key ];
1380 if ( 'video' === $atts['type'] ) {
1381 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1382 $width = $meta['width'];
1383 $height = $meta['height'];
1384 $theme_height = round( ( $height * $theme_width ) / $width );
1386 $width = $default_width;
1387 $height = $default_height;
1390 $track['dimensions'] = array(
1391 'original' => compact( 'width', 'height' ),
1393 'width' => $theme_width,
1394 'height' => $theme_height
1400 if ( $atts['images'] ) {
1401 $thumb_id = get_post_thumbnail_id( $attachment->ID );
1402 if ( ! empty( $thumb_id ) ) {
1403 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
1404 $track['image'] = compact( 'src', 'width', 'height' );
1405 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
1406 $track['thumb'] = compact( 'src', 'width', 'height' );
1408 $src = wp_mime_type_icon( $attachment->ID );
1411 $track['image'] = compact( 'src', 'width', 'height' );
1412 $track['thumb'] = compact( 'src', 'width', 'height' );
1418 $data['tracks'] = $tracks;
1420 $safe_type = esc_attr( $atts['type'] );
1421 $safe_style = esc_attr( $atts['style'] );
1425 if ( 1 === $instance ) {
1427 * Print and enqueue playlist scripts, styles, and JavaScript templates.
1431 * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
1432 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
1434 do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
1436 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
1437 <?php if ( 'audio' === $atts['type'] ): ?>
1438 <div class="wp-playlist-current-item"></div>
1440 <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
1441 echo (int) $theme_width;
1442 ?>"<?php if ( 'video' === $safe_type ):
1443 echo ' height="', (int) $theme_height, '"';
1445 echo ' style="visibility: hidden"';
1446 endif; ?>></<?php echo $safe_type ?>>
1447 <div class="wp-playlist-next"></div>
1448 <div class="wp-playlist-prev"></div>
1451 foreach ( $attachments as $att_id => $attachment ) {
1452 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
1456 <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
1459 return ob_get_clean();
1461 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
1464 * Provides a No-JS Flash fallback as a last resort for audio / video.
1468 * @param string $url The media element URL.
1469 * @return string Fallback HTML.
1471 function wp_mediaelement_fallback( $url ) {
1473 * Filter the Mediaelement fallback output for no-JS.
1477 * @param string $output Fallback output for no-JS.
1478 * @param string $url Media file URL.
1480 return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
1484 * Returns a filtered list of WP-supported audio formats.
1488 * @return array Supported audio formats.
1490 function wp_get_audio_extensions() {
1492 * Filter the list of supported audio formats.
1496 * @param array $extensions An array of support audio formats. Defaults are
1497 * 'mp3', 'ogg', 'wma', 'm4a', 'wav'.
1499 return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
1503 * Returns useful keys to use to lookup data from an attachment's stored metadata.
1507 * @param WP_Post $attachment The current attachment, provided for context.
1508 * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'.
1509 * @return array Key/value pairs of field keys to labels.
1511 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
1513 'artist' => __( 'Artist' ),
1514 'album' => __( 'Album' ),
1517 if ( 'display' === $context ) {
1518 $fields['genre'] = __( 'Genre' );
1519 $fields['year'] = __( 'Year' );
1520 $fields['length_formatted'] = _x( 'Length', 'video or audio' );
1521 } elseif ( 'js' === $context ) {
1522 $fields['bitrate'] = __( 'Bitrate' );
1523 $fields['bitrate_mode'] = __( 'Bitrate Mode' );
1527 * Filter the editable list of keys to look up data from an attachment's metadata.
1531 * @param array $fields Key/value pairs of field keys to labels.
1532 * @param WP_Post $attachment Attachment object.
1533 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
1535 return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
1538 * Builds the Audio shortcode output.
1540 * This implements the functionality of the Audio Shortcode for displaying
1541 * WordPress mp3s in a post.
1545 * @staticvar int $instance
1547 * @param array $attr {
1548 * Attributes of the audio shortcode.
1550 * @type string $src URL to the source of the audio file. Default empty.
1551 * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
1552 * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
1553 * @type string $preload The 'preload' attribute for the `<audio>` element. Default empty.
1554 * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
1555 * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
1557 * @param string $content Shortcode content.
1558 * @return string|void HTML content to display audio.
1560 function wp_audio_shortcode( $attr, $content = '' ) {
1561 $post_id = get_post() ? get_the_ID() : 0;
1563 static $instance = 0;
1567 * Filter the default audio shortcode output.
1569 * If the filtered output isn't empty, it will be used instead of generating the default audio template.
1573 * @param string $html Empty variable to be replaced with shortcode markup.
1574 * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
1575 * @param string $content Shortcode content.
1576 * @param int $instance Unique numeric ID of this audio shortcode instance.
1578 $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
1579 if ( '' !== $override ) {
1585 $default_types = wp_get_audio_extensions();
1586 $defaults_atts = array(
1592 foreach ( $default_types as $type ) {
1593 $defaults_atts[$type] = '';
1596 $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
1599 if ( ! empty( $atts['src'] ) ) {
1600 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
1601 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1602 return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
1605 array_unshift( $default_types, 'src' );
1607 foreach ( $default_types as $ext ) {
1608 if ( ! empty( $atts[ $ext ] ) ) {
1609 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
1610 if ( strtolower( $type['ext'] ) === $ext ) {
1618 $audios = get_attached_media( 'audio', $post_id );
1619 if ( empty( $audios ) ) {
1623 $audio = reset( $audios );
1624 $atts['src'] = wp_get_attachment_url( $audio->ID );
1625 if ( empty( $atts['src'] ) ) {
1629 array_unshift( $default_types, 'src' );
1633 * Filter the media library used for the audio shortcode.
1637 * @param string $library Media library used for the audio shortcode.
1639 $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
1640 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1641 wp_enqueue_style( 'wp-mediaelement' );
1642 wp_enqueue_script( 'wp-mediaelement' );
1646 * Filter the class attribute for the audio shortcode output container.
1650 * @param string $class CSS class or list of space-separated classes.
1653 'class' => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
1654 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
1655 'loop' => wp_validate_boolean( $atts['loop'] ),
1656 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
1657 'preload' => $atts['preload'],
1658 'style' => 'width: 100%; visibility: hidden;',
1661 // These ones should just be omitted altogether if they are blank
1662 foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
1663 if ( empty( $html_atts[$a] ) ) {
1664 unset( $html_atts[$a] );
1668 $attr_strings = array();
1669 foreach ( $html_atts as $k => $v ) {
1670 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1674 if ( 'mediaelement' === $library && 1 === $instance ) {
1675 $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
1677 $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
1680 $source = '<source type="%s" src="%s" />';
1681 foreach ( $default_types as $fallback ) {
1682 if ( ! empty( $atts[ $fallback ] ) ) {
1683 if ( empty( $fileurl ) ) {
1684 $fileurl = $atts[ $fallback ];
1686 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
1687 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
1688 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1692 if ( 'mediaelement' === $library ) {
1693 $html .= wp_mediaelement_fallback( $fileurl );
1695 $html .= '</audio>';
1698 * Filter the audio shortcode output.
1702 * @param string $html Audio shortcode HTML output.
1703 * @param array $atts Array of audio shortcode attributes.
1704 * @param string $audio Audio file.
1705 * @param int $post_id Post ID.
1706 * @param string $library Media library used for the audio shortcode.
1708 return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
1710 add_shortcode( 'audio', 'wp_audio_shortcode' );
1713 * Returns a filtered list of WP-supported video formats.
1717 * @return array List of supported video formats.
1719 function wp_get_video_extensions() {
1721 * Filter the list of supported video formats.
1725 * @param array $extensions An array of support video formats. Defaults are
1726 * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
1728 return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
1732 * Builds the Video shortcode output.
1734 * This implements the functionality of the Video Shortcode for displaying
1735 * WordPress mp4s in a post.
1739 * @global int $content_width
1740 * @staticvar int $instance
1742 * @param array $attr {
1743 * Attributes of the shortcode.
1745 * @type string $src URL to the source of the video file. Default empty.
1746 * @type int $height Height of the video embed in pixels. Default 360.
1747 * @type int $width Width of the video embed in pixels. Default $content_width or 640.
1748 * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
1749 * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
1750 * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
1751 * @type string $preload The 'preload' attribute for the `<video>` element.
1752 * Default 'metadata'.
1753 * @type string $class The 'class' attribute for the `<video>` element.
1754 * Default 'wp-video-shortcode'.
1756 * @param string $content Shortcode content.
1757 * @return string|void HTML content to display video.
1759 function wp_video_shortcode( $attr, $content = '' ) {
1760 global $content_width;
1761 $post_id = get_post() ? get_the_ID() : 0;
1763 static $instance = 0;
1767 * Filter the default video shortcode output.
1769 * If the filtered output isn't empty, it will be used instead of generating
1770 * the default video template.
1774 * @see wp_video_shortcode()
1776 * @param string $html Empty variable to be replaced with shortcode markup.
1777 * @param array $attr Attributes of the video shortcode.
1778 * @param string $content Video shortcode content.
1779 * @param int $instance Unique numeric ID of this video shortcode instance.
1781 $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
1782 if ( '' !== $override ) {
1788 $default_types = wp_get_video_extensions();
1789 $defaults_atts = array(
1794 'preload' => 'metadata',
1799 foreach ( $default_types as $type ) {
1800 $defaults_atts[$type] = '';
1803 $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
1806 // shrink the video so it isn't huge in the admin
1807 if ( $atts['width'] > $defaults_atts['width'] ) {
1808 $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
1809 $atts['width'] = $defaults_atts['width'];
1812 // if the video is bigger than the theme
1813 if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
1814 $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
1815 $atts['width'] = $content_width;
1819 $is_vimeo = $is_youtube = false;
1820 $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
1821 $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
1824 if ( ! empty( $atts['src'] ) ) {
1825 $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
1826 $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
1827 if ( ! $is_youtube && ! $is_vimeo ) {
1828 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
1829 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1830 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
1835 wp_enqueue_script( 'froogaloop' );
1839 array_unshift( $default_types, 'src' );
1841 foreach ( $default_types as $ext ) {
1842 if ( ! empty( $atts[ $ext ] ) ) {
1843 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
1844 if ( strtolower( $type['ext'] ) === $ext ) {
1852 $videos = get_attached_media( 'video', $post_id );
1853 if ( empty( $videos ) ) {
1857 $video = reset( $videos );
1858 $atts['src'] = wp_get_attachment_url( $video->ID );
1859 if ( empty( $atts['src'] ) ) {
1863 array_unshift( $default_types, 'src' );
1867 * Filter the media library used for the video shortcode.
1871 * @param string $library Media library used for the video shortcode.
1873 $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
1874 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1875 wp_enqueue_style( 'wp-mediaelement' );
1876 wp_enqueue_script( 'wp-mediaelement' );
1880 * Filter the class attribute for the video shortcode output container.
1884 * @param string $class CSS class or list of space-separated classes.
1887 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
1888 'id' => sprintf( 'video-%d-%d', $post_id, $instance ),
1889 'width' => absint( $atts['width'] ),
1890 'height' => absint( $atts['height'] ),
1891 'poster' => esc_url( $atts['poster'] ),
1892 'loop' => wp_validate_boolean( $atts['loop'] ),
1893 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
1894 'preload' => $atts['preload'],
1897 // These ones should just be omitted altogether if they are blank
1898 foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
1899 if ( empty( $html_atts[$a] ) ) {
1900 unset( $html_atts[$a] );
1904 $attr_strings = array();
1905 foreach ( $html_atts as $k => $v ) {
1906 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1910 if ( 'mediaelement' === $library && 1 === $instance ) {
1911 $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
1913 $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
1916 $source = '<source type="%s" src="%s" />';
1917 foreach ( $default_types as $fallback ) {
1918 if ( ! empty( $atts[ $fallback ] ) ) {
1919 if ( empty( $fileurl ) ) {
1920 $fileurl = $atts[ $fallback ];
1922 if ( 'src' === $fallback && $is_youtube ) {
1923 $type = array( 'type' => 'video/youtube' );
1924 } elseif ( 'src' === $fallback && $is_vimeo ) {
1925 $type = array( 'type' => 'video/vimeo' );
1927 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
1929 $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
1930 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1934 if ( ! empty( $content ) ) {
1935 if ( false !== strpos( $content, "\n" ) ) {
1936 $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
1938 $html .= trim( $content );
1941 if ( 'mediaelement' === $library ) {
1942 $html .= wp_mediaelement_fallback( $fileurl );
1944 $html .= '</video>';
1947 if ( ! empty( $atts['width'] ) ) {
1948 $width_rule = sprintf( 'width: %dpx; ', $atts['width'] );
1950 $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
1953 * Filter the output of the video shortcode.
1957 * @param string $output Video shortcode HTML output.
1958 * @param array $atts Array of video shortcode attributes.
1959 * @param string $video Video file.
1960 * @param int $post_id Post ID.
1961 * @param string $library Media library used for the video shortcode.
1963 return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
1965 add_shortcode( 'video', 'wp_video_shortcode' );
1968 * Displays previous image link that has the same post parent.
1972 * @see adjacent_image_link()
1974 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
1975 * 0 or 'none' will default to 'post_title' or `$text`. Default 'thumbnail'.
1976 * @param string $text Optional. Link text. Default false.
1978 function previous_image_link( $size = 'thumbnail', $text = false ) {
1979 adjacent_image_link(true, $size, $text);
1983 * Displays next image link that has the same post parent.
1987 * @see adjacent_image_link()
1989 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
1990 * 0 or 'none' will default to 'post_title' or `$text`. Default 'thumbnail'.
1991 * @param string $text Optional. Link text. Default false.
1993 function next_image_link($size = 'thumbnail', $text = false) {
1994 adjacent_image_link(false, $size, $text);
1998 * Displays next or previous image link that has the same post parent.
2000 * Retrieves the current attachment object from the $post global.
2004 * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
2005 * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
2006 * Default 'thumbnail'.
2007 * @param bool $text Optional. Link text. Default false.
2009 function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
2011 $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' ) ) );
2013 foreach ( $attachments as $k => $attachment ) {
2014 if ( $attachment->ID == $post->ID ) {
2022 if ( $attachments ) {
2023 $k = $prev ? $k - 1 : $k + 1;
2025 if ( isset( $attachments[ $k ] ) ) {
2026 $attachment_id = $attachments[ $k ]->ID;
2027 $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
2031 $adjacent = $prev ? 'previous' : 'next';
2034 * Filter the adjacent image link.
2036 * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
2037 * either 'next', or 'previous'.
2041 * @param string $output Adjacent image HTML markup.
2042 * @param int $attachment_id Attachment ID
2043 * @param string $size Image size.
2044 * @param string $text Link text.
2046 echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
2050 * Retrieves taxonomies attached to given the attachment.
2054 * @param int|array|object $attachment Attachment ID, data array, or data object.
2055 * @return array Empty array on failure. List of taxonomies on success.
2057 function get_attachment_taxonomies( $attachment ) {
2058 if ( is_int( $attachment ) ) {
2059 $attachment = get_post( $attachment );
2060 } elseif ( is_array( $attachment ) ) {
2061 $attachment = (object) $attachment;
2063 if ( ! is_object($attachment) )
2066 $filename = basename($attachment->guid);
2068 $objects = array('attachment');
2070 if ( false !== strpos($filename, '.') )
2071 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
2072 if ( !empty($attachment->post_mime_type) ) {
2073 $objects[] = 'attachment:' . $attachment->post_mime_type;
2074 if ( false !== strpos($attachment->post_mime_type, '/') )
2075 foreach ( explode('/', $attachment->post_mime_type) as $token )
2076 if ( !empty($token) )
2077 $objects[] = "attachment:$token";
2080 $taxonomies = array();
2081 foreach ( $objects as $object )
2082 if ( $taxes = get_object_taxonomies($object) )
2083 $taxonomies = array_merge($taxonomies, $taxes);
2085 return array_unique($taxonomies);
2089 * Retrieves all of the taxonomy names that are registered for attachments.
2091 * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
2095 * @see get_taxonomies()
2097 * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
2099 * @return array The names of all taxonomy of $object_type.
2101 function get_taxonomies_for_attachments( $output = 'names' ) {
2102 $taxonomies = array();
2103 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
2104 foreach ( $taxonomy->object_type as $object_type ) {
2105 if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
2106 if ( 'names' == $output )
2107 $taxonomies[] = $taxonomy->name;
2109 $taxonomies[ $taxonomy->name ] = $taxonomy;
2119 * Create new GD image resource with transparency support
2121 * @todo: Deprecate if possible.
2125 * @param int $width Image width in pixels.
2126 * @param int $height Image height in pixels..
2127 * @return resource The GD image resource.
2129 function wp_imagecreatetruecolor($width, $height) {
2130 $img = imagecreatetruecolor($width, $height);
2131 if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
2132 imagealphablending($img, false);
2133 imagesavealpha($img, true);
2139 * Registers an embed handler.
2141 * Should probably only be used for sites that do not support oEmbed.
2145 * @global WP_Embed $wp_embed
2147 * @param string $id An internal ID/name for the handler. Needs to be unique.
2148 * @param string $regex The regex that will be used to see if this handler should be used for a URL.
2149 * @param callback $callback The callback function that will be called if the regex is matched.
2150 * @param int $priority Optional. Used to specify the order in which the registered handlers will
2151 * be tested. Default 10.
2153 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
2155 $wp_embed->register_handler( $id, $regex, $callback, $priority );
2159 * Unregisters a previously-registered embed handler.
2163 * @global WP_Embed $wp_embed
2165 * @param string $id The handler ID that should be removed.
2166 * @param int $priority Optional. The priority of the handler to be removed. Default 10.
2168 function wp_embed_unregister_handler( $id, $priority = 10 ) {
2170 $wp_embed->unregister_handler( $id, $priority );
2174 * Create default array of embed parameters.
2176 * The width defaults to the content width as specified by the theme. If the
2177 * theme does not specify a content width, then 500px is used.
2179 * The default height is 1.5 times the width, or 1000px, whichever is smaller.
2181 * The 'embed_defaults' filter can be used to adjust either of these values.
2185 * @global int $content_width
2187 * @param string $url Optional. The URL that should be embedded. Default empty.
2189 * @return array Default embed parameters.
2191 function wp_embed_defaults( $url = '' ) {
2192 if ( ! empty( $GLOBALS['content_width'] ) )
2193 $width = (int) $GLOBALS['content_width'];
2195 if ( empty( $width ) )
2198 $height = min( ceil( $width * 1.5 ), 1000 );
2201 * Filter the default array of embed dimensions.
2205 * @param int $width Width of the embed in pixels.
2206 * @param int $height Height of the embed in pixels.
2207 * @param string $url The URL that should be embedded.
2209 return apply_filters( 'embed_defaults', compact( 'width', 'height' ), $url );
2213 * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
2217 * @see wp_constrain_dimensions()
2219 * @param int $example_width The width of an example embed.
2220 * @param int $example_height The height of an example embed.
2221 * @param int $max_width The maximum allowed width.
2222 * @param int $max_height The maximum allowed height.
2223 * @return array The maximum possible width and height based on the example ratio.
2225 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
2226 $example_width = (int) $example_width;
2227 $example_height = (int) $example_height;
2228 $max_width = (int) $max_width;
2229 $max_height = (int) $max_height;
2231 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
2235 * Attempts to fetch the embed HTML for a provided URL using oEmbed.
2241 * @param string $url The URL that should be embedded.
2242 * @param array $args Optional. Additional arguments and parameters for retrieving embed HTML.
2244 * @return false|string False on failure or the embed HTML on success.
2246 function wp_oembed_get( $url, $args = '' ) {
2247 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2248 $oembed = _wp_oembed_get_object();
2249 return $oembed->get_html( $url, $args );
2253 * Adds a URL format and oEmbed provider URL pair.
2259 * @param string $format The format of URL that this provider can handle. You can use asterisks
2261 * @param string $provider The URL to the oEmbed provider.
2262 * @param boolean $regex Optional. Whether the `$format` parameter is in a RegEx format. Default false.
2264 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
2265 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2267 if ( did_action( 'plugins_loaded' ) ) {
2268 $oembed = _wp_oembed_get_object();
2269 $oembed->providers[$format] = array( $provider, $regex );
2271 WP_oEmbed::_add_provider_early( $format, $provider, $regex );
2276 * Removes an oEmbed provider.
2282 * @param string $format The URL format for the oEmbed provider to remove.
2283 * @return bool Was the provider removed successfully?
2285 function wp_oembed_remove_provider( $format ) {
2286 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2288 if ( did_action( 'plugins_loaded' ) ) {
2289 $oembed = _wp_oembed_get_object();
2291 if ( isset( $oembed->providers[ $format ] ) ) {
2292 unset( $oembed->providers[ $format ] );
2296 WP_oEmbed::_remove_provider_early( $format );
2303 * Determines if default embed handlers should be loaded.
2305 * Checks to make sure that the embeds library hasn't already been loaded. If
2306 * it hasn't, then it will load the embeds library.
2310 * @see wp_embed_register_handler()
2312 function wp_maybe_load_embeds() {
2314 * Filter whether to load the default embed handlers.
2316 * Returning a falsey value will prevent loading the default embed handlers.
2320 * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
2322 if ( ! apply_filters( 'load_default_embeds', true ) ) {
2326 wp_embed_register_handler( 'youtube_embed_url', '#https?://(www.)?youtube\.com/(?:v|embed)/([^/]+)#i', 'wp_embed_handler_youtube' );
2328 wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
2331 * Filter the audio embed handler callback.
2335 * @param callback $handler Audio embed handler callback function.
2337 wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
2340 * Filter the video embed handler callback.
2344 * @param callback $handler Video embed handler callback function.
2346 wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
2350 * The Google Video embed handler callback.
2352 * Google Video does not support oEmbed.
2354 * @see WP_Embed::register_handler()
2355 * @see WP_Embed::shortcode()
2357 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2358 * @param array $attr Embed attributes.
2359 * @param string $url The original URL that was matched by the regex.
2360 * @param array $rawattr The original unmodified attributes.
2361 * @return string The embed HTML.
2363 function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
2364 // If the user supplied a fixed width AND height, use it
2365 if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
2366 $width = (int) $rawattr['width'];
2367 $height = (int) $rawattr['height'];
2369 list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
2373 * Filter the Google Video embed output.
2377 * @param string $html Google Video HTML embed markup.
2378 * @param array $matches The RegEx matches from the provided regex.
2379 * @param array $attr An array of embed attributes.
2380 * @param string $url The original URL that was matched by the regex.
2381 * @param array $rawattr The original unmodified attributes.
2383 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 );
2387 * YouTube iframe embed handler callback.
2389 * Catches YouTube iframe embed URLs that are not parsable by oEmbed but can be translated into a URL that is.
2393 * @global WP_Embed $wp_embed
2395 * @param array $matches The RegEx matches from the provided regex when calling
2396 * wp_embed_register_handler().
2397 * @param array $attr Embed attributes.
2398 * @param string $url The original URL that was matched by the regex.
2399 * @param array $rawattr The original unmodified attributes.
2400 * @return string The embed HTML.
2402 function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
2404 $embed = $wp_embed->autoembed( "https://youtube.com/watch?v={$matches[2]}" );
2407 * Filter the YoutTube embed output.
2411 * @see wp_embed_handler_youtube()
2413 * @param string $embed YouTube embed output.
2414 * @param array $attr An array of embed attributes.
2415 * @param string $url The original URL that was matched by the regex.
2416 * @param array $rawattr The original unmodified attributes.
2418 return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
2422 * Audio embed handler callback.
2426 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2427 * @param array $attr Embed attributes.
2428 * @param string $url The original URL that was matched by the regex.
2429 * @param array $rawattr The original unmodified attributes.
2430 * @return string The embed HTML.
2432 function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
2433 $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
2436 * Filter the audio embed output.
2440 * @param string $audio Audio embed output.
2441 * @param array $attr An array of embed attributes.
2442 * @param string $url The original URL that was matched by the regex.
2443 * @param array $rawattr The original unmodified attributes.
2445 return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
2449 * Video embed handler callback.
2453 * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
2454 * @param array $attr Embed attributes.
2455 * @param string $url The original URL that was matched by the regex.
2456 * @param array $rawattr The original unmodified attributes.
2457 * @return string The embed HTML.
2459 function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
2461 if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
2462 $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
2463 $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
2465 $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
2468 * Filter the video embed output.
2472 * @param string $video Video embed output.
2473 * @param array $attr An array of embed attributes.
2474 * @param string $url The original URL that was matched by the regex.
2475 * @param array $rawattr The original unmodified attributes.
2477 return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
2481 * Converts a shorthand byte value to an integer byte value.
2485 * @param string $size A shorthand byte value.
2486 * @return int An integer byte value.
2488 function wp_convert_hr_to_bytes( $size ) {
2489 $size = strtolower( $size );
2490 $bytes = (int) $size;
2491 if ( strpos( $size, 'k' ) !== false )
2492 $bytes = intval( $size ) * 1024;
2493 elseif ( strpos( $size, 'm' ) !== false )
2494 $bytes = intval($size) * 1024 * 1024;
2495 elseif ( strpos( $size, 'g' ) !== false )
2496 $bytes = intval( $size ) * 1024 * 1024 * 1024;
2501 * Determines the maximum upload size allowed in php.ini.
2505 * @return int Allowed upload size.
2507 function wp_max_upload_size() {
2508 $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2509 $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2512 * Filter the maximum upload size allowed in php.ini.
2516 * @param int $size Max upload size limit in bytes.
2517 * @param int $u_bytes Maximum upload filesize in bytes.
2518 * @param int $p_bytes Maximum size of POST data in bytes.
2520 return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2524 * Returns a WP_Image_Editor instance and loads file into it.
2528 * @param string $path Path to the file to load.
2529 * @param array $args Optional. Additional arguments for retrieving the image editor.
2530 * Default empty array.
2531 * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
2534 function wp_get_image_editor( $path, $args = array() ) {
2535 $args['path'] = $path;
2537 if ( ! isset( $args['mime_type'] ) ) {
2538 $file_info = wp_check_filetype( $args['path'] );
2540 // If $file_info['type'] is false, then we let the editor attempt to
2541 // figure out the file type, rather than forcing a failure based on extension.
2542 if ( isset( $file_info ) && $file_info['type'] )
2543 $args['mime_type'] = $file_info['type'];
2546 $implementation = _wp_image_editor_choose( $args );
2548 if ( $implementation ) {
2549 $editor = new $implementation( $path );
2550 $loaded = $editor->load();
2552 if ( is_wp_error( $loaded ) )
2558 return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
2562 * Tests whether there is an editor that supports a given mime type or methods.
2566 * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
2567 * Default empty array.
2568 * @return bool True if an eligible editor is found; false otherwise.
2570 function wp_image_editor_supports( $args = array() ) {
2571 return (bool) _wp_image_editor_choose( $args );
2575 * Tests which editors are capable of supporting the request.
2580 * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
2581 * @return string|false Class name for the first editor that claims to support the request. False if no
2582 * editor claims to support the request.
2584 function _wp_image_editor_choose( $args = array() ) {
2585 require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
2586 require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
2587 require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
2590 * Filter the list of image editing library classes.
2594 * @param array $image_editors List of available image editors. Defaults are
2595 * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
2597 $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
2599 foreach ( $implementations as $implementation ) {
2600 if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
2603 if ( isset( $args['mime_type'] ) &&
2605 array( $implementation, 'supports_mime_type' ),
2606 $args['mime_type'] ) ) {
2610 if ( isset( $args['methods'] ) &&
2611 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
2615 return $implementation;
2622 * Prints default plupload arguments.
2626 function wp_plupload_default_settings() {
2627 $wp_scripts = wp_scripts();
2629 $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
2630 if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
2633 $max_upload_size = wp_max_upload_size();
2636 'runtimes' => 'html5,flash,silverlight,html4',
2637 'file_data_name' => 'async-upload', // key passed to $_FILE.
2638 'url' => admin_url( 'async-upload.php', 'relative' ),
2639 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
2640 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
2642 'max_file_size' => $max_upload_size . 'b',
2646 // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
2647 // when enabled. See #29602.
2648 if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
2649 strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
2651 $defaults['multi_selection'] = false;
2655 * Filter the Plupload default settings.
2659 * @param array $defaults Default Plupload settings array.
2661 $defaults = apply_filters( 'plupload_default_settings', $defaults );
2664 'action' => 'upload-attachment',
2668 * Filter the Plupload default parameters.
2672 * @param array $params Default Plupload parameters array.
2674 $params = apply_filters( 'plupload_default_params', $params );
2675 $params['_wpnonce'] = wp_create_nonce( 'media-form' );
2676 $defaults['multipart_params'] = $params;
2679 'defaults' => $defaults,
2681 'mobile' => wp_is_mobile(),
2682 'supported' => _device_can_upload(),
2684 'limitExceeded' => is_multisite() && ! is_upload_space_available()
2687 $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
2690 $script = "$data\n$script";
2692 $wp_scripts->add_data( 'wp-plupload', 'data', $script );
2696 * Prepares an attachment post object for JS, where it is expected
2697 * to be JSON-encoded and fit into an Attachment model.
2701 * @param mixed $attachment Attachment ID or object.
2702 * @return array|void Array of attachment details.
2704 function wp_prepare_attachment_for_js( $attachment ) {
2705 if ( ! $attachment = get_post( $attachment ) )
2708 if ( 'attachment' != $attachment->post_type )
2711 $meta = wp_get_attachment_metadata( $attachment->ID );
2712 if ( false !== strpos( $attachment->post_mime_type, '/' ) )
2713 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
2715 list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
2717 $attachment_url = wp_get_attachment_url( $attachment->ID );
2720 'id' => $attachment->ID,
2721 'title' => $attachment->post_title,
2722 'filename' => wp_basename( get_attached_file( $attachment->ID ) ),
2723 'url' => $attachment_url,
2724 'link' => get_attachment_link( $attachment->ID ),
2725 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
2726 'author' => $attachment->post_author,
2727 'description' => $attachment->post_content,
2728 'caption' => $attachment->post_excerpt,
2729 'name' => $attachment->post_name,
2730 'status' => $attachment->post_status,
2731 'uploadedTo' => $attachment->post_parent,
2732 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
2733 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
2734 'menuOrder' => $attachment->menu_order,
2735 'mime' => $attachment->post_mime_type,
2737 'subtype' => $subtype,
2738 'icon' => wp_mime_type_icon( $attachment->ID ),
2739 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
2745 'editLink' => false,
2749 $author = new WP_User( $attachment->post_author );
2750 $response['authorName'] = $author->display_name;
2752 if ( $attachment->post_parent ) {
2753 $post_parent = get_post( $attachment->post_parent );
2755 $post_parent = false;
2758 if ( $post_parent ) {
2759 $parent_type = get_post_type_object( $post_parent->post_type );
2760 if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
2761 $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
2763 $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
2766 $attached_file = get_attached_file( $attachment->ID );
2767 if ( file_exists( $attached_file ) ) {
2768 $bytes = filesize( $attached_file );
2769 $response['filesizeInBytes'] = $bytes;
2770 $response['filesizeHumanReadable'] = size_format( $bytes );
2773 if ( current_user_can( 'edit_post', $attachment->ID ) ) {
2774 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
2775 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
2776 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
2779 if ( current_user_can( 'delete_post', $attachment->ID ) )
2780 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
2782 if ( $meta && 'image' === $type ) {
2785 /** This filter is documented in wp-admin/includes/media.php */
2786 $possible_sizes = apply_filters( 'image_size_names_choose', array(
2787 'thumbnail' => __('Thumbnail'),
2788 'medium' => __('Medium'),
2789 'large' => __('Large'),
2790 'full' => __('Full Size'),
2792 unset( $possible_sizes['full'] );
2794 // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
2795 // First: run the image_downsize filter. If it returns something, we can use its data.
2796 // If the filter does not return something, then image_downsize() is just an expensive
2797 // way to check the image metadata, which we do second.
2798 foreach ( $possible_sizes as $size => $label ) {
2800 /** This filter is documented in wp-includes/media.php */
2801 if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
2802 if ( ! $downsize[3] )
2804 $sizes[ $size ] = array(
2805 'height' => $downsize[2],
2806 'width' => $downsize[1],
2807 'url' => $downsize[0],
2808 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
2810 } elseif ( isset( $meta['sizes'][ $size ] ) ) {
2811 if ( ! isset( $base_url ) )
2812 $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
2814 // Nothing from the filter, so consult image metadata if we have it.
2815 $size_meta = $meta['sizes'][ $size ];
2817 // We have the actual image size, but might need to further constrain it if content_width is narrower.
2818 // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
2819 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
2821 $sizes[ $size ] = array(
2822 'height' => $height,
2824 'url' => $base_url . $size_meta['file'],
2825 'orientation' => $height > $width ? 'portrait' : 'landscape',
2830 $sizes['full'] = array( 'url' => $attachment_url );
2832 if ( isset( $meta['height'], $meta['width'] ) ) {
2833 $sizes['full']['height'] = $meta['height'];
2834 $sizes['full']['width'] = $meta['width'];
2835 $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
2838 $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
2839 } elseif ( $meta && 'video' === $type ) {
2840 if ( isset( $meta['width'] ) )
2841 $response['width'] = (int) $meta['width'];
2842 if ( isset( $meta['height'] ) )
2843 $response['height'] = (int) $meta['height'];
2846 if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
2847 if ( isset( $meta['length_formatted'] ) )
2848 $response['fileLength'] = $meta['length_formatted'];
2850 $response['meta'] = array();
2851 foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
2852 $response['meta'][ $key ] = false;
2854 if ( ! empty( $meta[ $key ] ) ) {
2855 $response['meta'][ $key ] = $meta[ $key ];
2859 $id = get_post_thumbnail_id( $attachment->ID );
2860 if ( ! empty( $id ) ) {
2861 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
2862 $response['image'] = compact( 'src', 'width', 'height' );
2863 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
2864 $response['thumb'] = compact( 'src', 'width', 'height' );
2866 $src = wp_mime_type_icon( $attachment->ID );
2869 $response['image'] = compact( 'src', 'width', 'height' );
2870 $response['thumb'] = compact( 'src', 'width', 'height' );
2874 if ( function_exists('get_compat_media_markup') )
2875 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
2878 * Filter the attachment data prepared for JavaScript.
2882 * @param array $response Array of prepared attachment data.
2883 * @param int|object $attachment Attachment ID or object.
2884 * @param array $meta Array of attachment meta data.
2886 return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
2890 * Enqueues all scripts, styles, settings, and templates necessary to use
2891 * all media JS APIs.
2895 * @global int $content_width
2896 * @global wpdb $wpdb
2897 * @global WP_Locale $wp_locale
2899 * @param array $args {
2900 * Arguments for enqueuing media scripts.
2902 * @type int|WP_Post A post object or ID.
2905 function wp_enqueue_media( $args = array() ) {
2906 // Enqueue me just once per page, please.
2907 if ( did_action( 'wp_enqueue_media' ) )
2910 global $content_width, $wpdb, $wp_locale;
2915 $args = wp_parse_args( $args, $defaults );
2917 // We're going to pass the old thickbox media tabs to `media_upload_tabs`
2918 // to ensure plugins will work. We will then unset those tabs.
2920 // handler action suffix => tab label
2927 /** This filter is documented in wp-admin/includes/media.php */
2928 $tabs = apply_filters( 'media_upload_tabs', $tabs );
2929 unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
2932 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
2933 'align' => get_option( 'image_default_align' ), // empty default
2934 'size' => get_option( 'image_default_size' ), // empty default
2937 $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
2938 $mimes = get_allowed_mime_types();
2939 $ext_mimes = array();
2940 foreach ( $exts as $ext ) {
2941 foreach ( $mimes as $ext_preg => $mime_match ) {
2942 if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
2943 $ext_mimes[ $ext ] = $mime_match;
2949 $has_audio = $wpdb->get_var( "
2952 WHERE post_type = 'attachment'
2953 AND post_mime_type LIKE 'audio%'
2956 $has_video = $wpdb->get_var( "
2959 WHERE post_type = 'attachment'
2960 AND post_mime_type LIKE 'video%'
2963 $months = $wpdb->get_results( $wpdb->prepare( "
2964 SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
2966 WHERE post_type = %s
2967 ORDER BY post_date DESC
2968 ", 'attachment' ) );
2969 foreach ( $months as $month_year ) {
2970 $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
2975 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
2976 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
2977 /** This filter is documented in wp-admin/includes/media.php */
2978 'captions' => ! apply_filters( 'disable_captions', '' ),
2980 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
2985 'defaultProps' => $props,
2986 'attachmentCounts' => array(
2987 'audio' => ( $has_audio ) ? 1 : 0,
2988 'video' => ( $has_video ) ? 1 : 0
2990 'embedExts' => $exts,
2991 'embedMimes' => $ext_mimes,
2992 'contentWidth' => $content_width,
2993 'months' => $months,
2994 'mediaTrash' => MEDIA_TRASH ? 1 : 0
2998 if ( isset( $args['post'] ) ) {
2999 $post = get_post( $args['post'] );
3000 $settings['post'] = array(
3002 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
3005 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
3006 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
3007 if ( wp_attachment_is( 'audio', $post ) ) {
3008 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
3009 } elseif ( wp_attachment_is( 'video', $post ) ) {
3010 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
3014 if ( $thumbnail_support ) {
3015 $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
3016 $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
3020 $hier = $post && is_post_type_hierarchical( $post->post_type );
3023 $post_type_object = get_post_type_object( $post->post_type );
3025 $post_type_object = get_post_type_object( 'post' );
3030 'url' => __( 'URL' ),
3031 'addMedia' => __( 'Add Media' ),
3032 'search' => __( 'Search' ),
3033 'select' => __( 'Select' ),
3034 'cancel' => __( 'Cancel' ),
3035 'update' => __( 'Update' ),
3036 'replace' => __( 'Replace' ),
3037 'remove' => __( 'Remove' ),
3038 'back' => __( 'Back' ),
3039 /* translators: This is a would-be plural string used in the media manager.
3040 If there is not a word you can use in your language to avoid issues with the
3041 lack of plural support here, turn it into "selected: %d" then translate it.
3043 'selected' => __( '%d selected' ),
3044 'dragInfo' => __( 'Drag and drop to reorder media files.' ),
3047 'uploadFilesTitle' => __( 'Upload Files' ),
3048 'uploadImagesTitle' => __( 'Upload Images' ),
3051 'mediaLibraryTitle' => __( 'Media Library' ),
3052 'insertMediaTitle' => __( 'Insert Media' ),
3053 'createNewGallery' => __( 'Create a new gallery' ),
3054 'createNewPlaylist' => __( 'Create a new playlist' ),
3055 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
3056 'returnToLibrary' => __( '← Return to library' ),
3057 'allMediaItems' => __( 'All media items' ),
3058 'allDates' => __( 'All dates' ),
3059 'noItemsFound' => __( 'No items found.' ),
3060 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
3061 'unattached' => __( 'Unattached' ),
3062 'trash' => _x( 'Trash', 'noun' ),
3063 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
3064 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
3065 'warnBulkDelete' => __( "You are about to permanently delete these items.\n 'Cancel' to stop, 'OK' to delete." ),
3066 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
3067 'bulkSelect' => __( 'Bulk Select' ),
3068 'cancelSelection' => __( 'Cancel Selection' ),
3069 'trashSelected' => __( 'Trash Selected' ),
3070 'untrashSelected' => __( 'Untrash Selected' ),
3071 'deleteSelected' => __( 'Delete Selected' ),
3072 'deletePermanently' => __( 'Delete Permanently' ),
3073 'apply' => __( 'Apply' ),
3074 'filterByDate' => __( 'Filter by date' ),
3075 'filterByType' => __( 'Filter by type' ),
3076 'searchMediaLabel' => __( 'Search Media' ),
3077 'noMedia' => __( 'No media attachments found.' ),
3080 'attachmentDetails' => __( 'Attachment Details' ),
3083 'insertFromUrlTitle' => __( 'Insert from URL' ),
3086 'setFeaturedImageTitle' => $post_type_object->labels->featured_image,
3087 'setFeaturedImage' => $post_type_object->labels->set_featured_image,
3090 'createGalleryTitle' => __( 'Create Gallery' ),
3091 'editGalleryTitle' => __( 'Edit Gallery' ),
3092 'cancelGalleryTitle' => __( '← Cancel Gallery' ),
3093 'insertGallery' => __( 'Insert gallery' ),
3094 'updateGallery' => __( 'Update gallery' ),
3095 'addToGallery' => __( 'Add to gallery' ),
3096 'addToGalleryTitle' => __( 'Add to Gallery' ),
3097 'reverseOrder' => __( 'Reverse order' ),
3100 'imageDetailsTitle' => __( 'Image Details' ),
3101 'imageReplaceTitle' => __( 'Replace Image' ),
3102 'imageDetailsCancel' => __( 'Cancel Edit' ),
3103 'editImage' => __( 'Edit Image' ),
3106 'chooseImage' => __( 'Choose Image' ),
3107 'selectAndCrop' => __( 'Select and Crop' ),
3108 'skipCropping' => __( 'Skip Cropping' ),
3109 'cropImage' => __( 'Crop Image' ),
3110 'cropYourImage' => __( 'Crop your image' ),
3111 'cropping' => __( 'Cropping…' ),
3112 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
3113 'cropError' => __( 'There has been an error cropping your image.' ),
3116 'audioDetailsTitle' => __( 'Audio Details' ),
3117 'audioReplaceTitle' => __( 'Replace Audio' ),
3118 'audioAddSourceTitle' => __( 'Add Audio Source' ),
3119 'audioDetailsCancel' => __( 'Cancel Edit' ),
3122 'videoDetailsTitle' => __( 'Video Details' ),
3123 'videoReplaceTitle' => __( 'Replace Video' ),
3124 'videoAddSourceTitle' => __( 'Add Video Source' ),
3125 'videoDetailsCancel' => __( 'Cancel Edit' ),
3126 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
3127 'videoAddTrackTitle' => __( 'Add Subtitles' ),
3130 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
3131 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
3132 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
3133 'cancelPlaylistTitle' => __( '← Cancel Audio Playlist' ),
3134 'insertPlaylist' => __( 'Insert audio playlist' ),
3135 'updatePlaylist' => __( 'Update audio playlist' ),
3136 'addToPlaylist' => __( 'Add to audio playlist' ),
3137 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
3140 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
3141 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
3142 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
3143 'cancelVideoPlaylistTitle' => __( '← Cancel Video Playlist' ),
3144 'insertVideoPlaylist' => __( 'Insert video playlist' ),
3145 'updateVideoPlaylist' => __( 'Update video playlist' ),
3146 'addToVideoPlaylist' => __( 'Add to video playlist' ),
3147 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
3151 * Filter the media view settings.
3155 * @param array $settings List of media view settings.
3156 * @param WP_Post $post Post object.
3158 $settings = apply_filters( 'media_view_settings', $settings, $post );
3161 * Filter the media view strings.
3165 * @param array $strings List of media view strings.
3166 * @param WP_Post $post Post object.
3168 $strings = apply_filters( 'media_view_strings', $strings, $post );
3170 $strings['settings'] = $settings;
3172 // Ensure we enqueue media-editor first, that way media-views is
3173 // registered internally before we try to localize it. see #24724.
3174 wp_enqueue_script( 'media-editor' );
3175 wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
3177 wp_enqueue_script( 'media-audiovideo' );
3178 wp_enqueue_style( 'media-views' );
3180 wp_enqueue_script( 'mce-view' );
3181 wp_enqueue_script( 'image-edit' );
3183 wp_enqueue_style( 'imgareaselect' );
3184 wp_plupload_default_settings();
3186 require_once ABSPATH . WPINC . '/media-template.php';
3187 add_action( 'admin_footer', 'wp_print_media_templates' );
3188 add_action( 'wp_footer', 'wp_print_media_templates' );
3189 add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
3192 * Fires at the conclusion of wp_enqueue_media().
3196 do_action( 'wp_enqueue_media' );
3200 * Retrieves media attached to the passed post.
3204 * @param string $type Mime type.
3205 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3206 * @return array Found attachments.
3208 function get_attached_media( $type, $post = 0 ) {
3209 if ( ! $post = get_post( $post ) )
3213 'post_parent' => $post->ID,
3214 'post_type' => 'attachment',
3215 'post_mime_type' => $type,
3216 'posts_per_page' => -1,
3217 'orderby' => 'menu_order',
3222 * Filter arguments used to retrieve media attached to the given post.
3226 * @param array $args Post query arguments.
3227 * @param string $type Mime type of the desired media.
3228 * @param mixed $post Post ID or object.
3230 $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
3232 $children = get_children( $args );
3235 * Filter the list of media attached to the given post.
3239 * @param array $children Associative array of media attached to the given post.
3240 * @param string $type Mime type of the media desired.
3241 * @param mixed $post Post ID or object.
3243 return (array) apply_filters( 'get_attached_media', $children, $type, $post );
3247 * Check the content blob for an audio, video, object, embed, or iframe tags.
3251 * @param string $content A string which might contain media data.
3252 * @param array $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
3253 * @return array A list of found HTML media embeds.
3255 function get_media_embedded_in_content( $content, $types = null ) {
3259 * Filter the embedded media types that are allowed to be returned from the content blob.
3263 * @param array $allowed_media_types An array of allowed media types. Default media types are
3264 * 'audio', 'video', 'object', 'embed', and 'iframe'.
3266 $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
3268 if ( ! empty( $types ) ) {
3269 if ( ! is_array( $types ) ) {
3270 $types = array( $types );
3273 $allowed_media_types = array_intersect( $allowed_media_types, $types );
3276 $tags = implode( '|', $allowed_media_types );
3278 if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
3279 foreach ( $matches[0] as $match ) {
3288 * Retrieves galleries from the passed post's content.
3292 * @param int|WP_Post $post Post ID or object.
3293 * @param bool $html Optional. Whether to return HTML or data in the array. Default true.
3294 * @return array A list of arrays, each containing gallery data and srcs parsed
3295 * from the expanded shortcode.
3297 function get_post_galleries( $post, $html = true ) {
3298 if ( ! $post = get_post( $post ) )
3301 if ( ! has_shortcode( $post->post_content, 'gallery' ) )
3304 $galleries = array();
3305 if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
3306 foreach ( $matches as $shortcode ) {
3307 if ( 'gallery' === $shortcode[2] ) {
3310 $gallery = do_shortcode_tag( $shortcode );
3312 $galleries[] = $gallery;
3314 preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
3315 if ( ! empty( $src ) ) {
3316 foreach ( $src as $s )
3320 $data = shortcode_parse_atts( $shortcode[3] );
3321 $data['src'] = array_values( array_unique( $srcs ) );
3322 $galleries[] = $data;
3329 * Filter the list of all found galleries in the given post.
3333 * @param array $galleries Associative array of all found post galleries.
3334 * @param WP_Post $post Post object.
3336 return apply_filters( 'get_post_galleries', $galleries, $post );
3340 * Check a specified post's content for gallery and, if present, return the first
3344 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3345 * @param bool $html Optional. Whether to return HTML or data. Default is true.
3346 * @return string|array Gallery data and srcs parsed from the expanded shortcode.
3348 function get_post_gallery( $post = 0, $html = true ) {
3349 $galleries = get_post_galleries( $post, $html );
3350 $gallery = reset( $galleries );
3353 * Filter the first-found post gallery.
3357 * @param array $gallery The first-found post gallery.
3358 * @param int|WP_Post $post Post ID or object.
3359 * @param array $galleries Associative array of all found post galleries.
3361 return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
3365 * Retrieve the image srcs from galleries from a post's content, if present
3369 * @see get_post_galleries()
3371 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3372 * @return array A list of lists, each containing image srcs parsed.
3373 * from an expanded shortcode
3375 function get_post_galleries_images( $post = 0 ) {
3376 $galleries = get_post_galleries( $post, false );
3377 return wp_list_pluck( $galleries, 'src' );
3381 * Checks a post's content for galleries and return the image srcs for the first found gallery
3385 * @see get_post_gallery()
3387 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3388 * @return array A list of a gallery's image srcs in order.
3390 function get_post_gallery_images( $post = 0 ) {
3391 $gallery = get_post_gallery( $post, false );
3392 return empty( $gallery['src'] ) ? array() : $gallery['src'];
3396 * Maybe attempts to generate attachment metadata, if missing.
3400 * @param WP_Post $attachment Attachment object.
3402 function wp_maybe_generate_attachment_metadata( $attachment ) {
3403 if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
3407 $file = get_attached_file( $attachment_id );
3408 $meta = wp_get_attachment_metadata( $attachment_id );
3409 if ( empty( $meta ) && file_exists( $file ) ) {
3410 $_meta = get_post_meta( $attachment_id );
3411 $regeneration_lock = 'wp_generating_att_' . $attachment_id;
3412 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
3413 set_transient( $regeneration_lock, $file );
3414 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
3415 delete_transient( $regeneration_lock );
3421 * Tries to convert an attachment URL into a post ID.
3425 * @global wpdb $wpdb WordPress database abstraction object.
3427 * @param string $url The URL to resolve.
3428 * @return int The found post ID, or 0 on failure.
3430 function attachment_url_to_postid( $url ) {
3433 $dir = wp_upload_dir();
3436 if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
3437 $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
3440 $sql = $wpdb->prepare(
3441 "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
3444 $post_id = $wpdb->get_var( $sql );
3447 * Filter an attachment id found by URL.
3451 * @param int|null $post_id The post_id (if any) found by the function.
3452 * @param string $url The URL being looked up.
3454 $post_id = apply_filters( 'attachment_url_to_postid', $post_id, $url );
3456 return (int) $post_id;
3460 * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
3464 * @global string $wp_version
3466 * @return array The relevant CSS file URLs.
3468 function wpview_media_sandbox_styles() {
3469 $version = 'ver=' . $GLOBALS['wp_version'];
3470 $mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
3471 $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
3473 return array( $mediaelement, $wpmediaelement );