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 'editor_max_image_size', that will be called
22 * 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.
28 * @uses wp_constrain_dimensions() This function passes the widths and the heights.
30 * @param int $width Width of the image
31 * @param int $height Height of the image
32 * @param string|array $size Size of what the result image should be.
33 * @param context Could be 'display' (like in a theme) or 'edit' (like inserting into an editor)
34 * @return array Width and height of what the result image should resize to.
36 function image_constrain_size_for_editor($width, $height, $size = 'medium', $context = null ) {
37 global $content_width, $_wp_additional_image_sizes;
40 $context = is_admin() ? 'edit' : 'display';
42 if ( is_array($size) ) {
43 $max_width = $size[0];
44 $max_height = $size[1];
46 elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
47 $max_width = intval(get_option('thumbnail_size_w'));
48 $max_height = intval(get_option('thumbnail_size_h'));
49 // last chance thumbnail size defaults
50 if ( !$max_width && !$max_height ) {
55 elseif ( $size == 'medium' ) {
56 $max_width = intval(get_option('medium_size_w'));
57 $max_height = intval(get_option('medium_size_h'));
58 // if no width is set, default to the theme content width if available
60 elseif ( $size == 'large' ) {
61 // We're inserting a large size image into the editor. If it's a really
62 // big image we'll scale it down to fit reasonably within the editor
63 // itself, and within the theme's content width if it's known. The user
64 // can resize it in the editor if they wish.
65 $max_width = intval(get_option('large_size_w'));
66 $max_height = intval(get_option('large_size_h'));
67 if ( intval($content_width) > 0 )
68 $max_width = min( intval($content_width), $max_width );
69 } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
70 $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
71 $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
72 if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
73 $max_width = min( intval($content_width), $max_width );
75 // $size == 'full' has no constraint
78 $max_height = $height;
82 * Filter the maximum image size dimensions for the editor.
86 * @param array $max_image_size An array with the width as the first element,
87 * and the height as the second element.
88 * @param string|array $size Size of what the result image should be.
89 * @param string $context The context the image is being resized for.
90 * Possible values are 'display' (like in a theme)
91 * or 'edit' (like inserting into an editor).
93 list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
95 return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
99 * Retrieve width and height attributes using given width and height values.
101 * Both attributes are required in the sense that both parameters must have a
102 * value, but are optional in that if you set them to false or null, then they
103 * will not be added to the returned string.
105 * You can set the value using a string, but it will only take numeric values.
106 * If you wish to put 'px' after the numbers, then it will be stripped out of
111 * @param int|string $width Optional. Width attribute value.
112 * @param int|string $height Optional. Height attribute value.
113 * @return string HTML attributes for width and, or height.
115 function image_hwstring($width, $height) {
118 $out .= 'width="'.intval($width).'" ';
120 $out .= 'height="'.intval($height).'" ';
125 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
127 * Array with image url, width, height, and whether is intermediate size, in
128 * that order is returned on success is returned. $is_intermediate is true if
129 * $url is a resized image, false if it is the original.
131 * The URL might be the original image, or it might be a resized version. This
132 * function won't create a new resized copy, it will just return an already
133 * resized one if it exists.
135 * A plugin may use the 'image_downsize' filter to hook into and offer image
136 * resizing services for images. The hook must return an array with the same
137 * elements that are returned in the function. The first element being the URL
138 * to the new image that was resized.
142 * @param int $id Attachment ID for image.
143 * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
144 * @return bool|array False on failure, array on success.
146 function image_downsize($id, $size = 'medium') {
148 if ( !wp_attachment_is_image($id) )
152 * Filter whether to preempt the output of image_downsize().
154 * Passing a truthy value to the filter will effectively short-circuit
155 * down-sizing the image, returning that value as output instead.
159 * @param bool $downsize Whether to short-circuit the image downsize. Default false.
160 * @param int $id Attachment ID for image.
161 * @param array|string $size Size of image, either array or string. Default 'medium'.
163 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
167 $img_url = wp_get_attachment_url($id);
168 $meta = wp_get_attachment_metadata($id);
169 $width = $height = 0;
170 $is_intermediate = false;
171 $img_url_basename = wp_basename($img_url);
173 // try for a new style intermediate size
174 if ( $intermediate = image_get_intermediate_size($id, $size) ) {
175 $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
176 $width = $intermediate['width'];
177 $height = $intermediate['height'];
178 $is_intermediate = true;
180 elseif ( $size == 'thumbnail' ) {
181 // fall back to the old thumbnail
182 if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
183 $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
186 $is_intermediate = true;
189 if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
190 // any other type: use the real image
191 $width = $meta['width'];
192 $height = $meta['height'];
196 // we have the actual image size, but might need to further constrain it if content_width is narrower
197 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
199 return array( $img_url, $width, $height, $is_intermediate );
206 * Register a new image size.
208 * Cropping behavior for the image size is dependent on the value of $crop:
209 * 1. If false (default), images will be scaled, not cropped.
210 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
211 * - x_crop_position accepts 'left' 'center', or 'right'.
212 * - y_crop_position accepts 'top', 'center', or 'bottom'.
213 * Images will be cropped to the specified dimensions within the defined crop area.
214 * 3. If true, images will be cropped to the specified dimensions using center positions.
218 * @param string $name Image size identifier.
219 * @param int $width Image width in pixels.
220 * @param int $height Image height in pixels.
221 * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
222 * An array can specify positioning of the crop area. Default false.
223 * @return bool|array False, if no image was created. Metadata array on success.
225 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
226 global $_wp_additional_image_sizes;
228 $_wp_additional_image_sizes[ $name ] = array(
229 'width' => absint( $width ),
230 'height' => absint( $height ),
236 * Check if an image size exists.
240 * @param string $name The image size to check.
241 * @return bool True if the image size exists, false if not.
243 function has_image_size( $name ) {
244 global $_wp_additional_image_sizes;
246 return isset( $_wp_additional_image_sizes[ $name ] );
250 * Remove a new image size.
254 * @param string $name The image size to remove.
255 * @return bool True if the image size was successfully removed, false on failure.
257 function remove_image_size( $name ) {
258 global $_wp_additional_image_sizes;
260 if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
261 unset( $_wp_additional_image_sizes[ $name ] );
269 * Registers an image size for the post thumbnail.
272 * @see add_image_size() for details on cropping behavior.
274 * @param int $width Image width in pixels.
275 * @param int $height Image height in pixels.
276 * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
277 * An array can specify positioning of the crop area. Default false.
278 * @return bool|array False, if no image was created. Metadata array on success.
280 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
281 add_image_size( 'post-thumbnail', $width, $height, $crop );
285 * An <img src /> tag for an image attachment, scaling it down if requested.
287 * The filter 'get_image_tag_class' allows for changing the class name for the
288 * image without having to use regular expressions on the HTML content. The
289 * parameters are: what WordPress will use for the class, the Attachment ID,
290 * image align value, and the size the image should be.
292 * The second filter 'get_image_tag' has the HTML content, which can then be
293 * further manipulated by a plugin to change all attribute values and even HTML
298 * @param int $id Attachment ID.
299 * @param string $alt Image Description for the alt attribute.
300 * @param string $title Image Description for the title attribute.
301 * @param string $align Part of the class name for aligning the image.
302 * @param string $size Optional. Default is 'medium'.
303 * @return string HTML IMG element for given image attachment
305 function get_image_tag($id, $alt, $title, $align, $size='medium') {
307 list( $img_src, $width, $height ) = image_downsize($id, $size);
308 $hwstring = image_hwstring($width, $height);
310 $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
312 $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
315 * Filter the value of the attachment's image tag class attribute.
319 * @param string $class CSS class name or space-separated list of classes.
320 * @param int $id Attachment ID.
321 * @param string $align Part of the class name for aligning the image.
322 * @param string $size Optional. Default is 'medium'.
324 $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
326 $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
329 * Filter the HTML content for the image tag.
333 * @param string $html HTML content for the image.
334 * @param int $id Attachment ID.
335 * @param string $alt Alternate text.
336 * @param string $title Attachment title.
337 * @param string $align Part of the class name for aligning the image.
338 * @param string $size Optional. Default is 'medium'.
340 $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
346 * Calculates the new dimensions for a downsampled image.
348 * If either width or height are empty, no constraint is applied on
353 * @param int $current_width Current width of the image.
354 * @param int $current_height Current height of the image.
355 * @param int $max_width Optional. Maximum wanted width.
356 * @param int $max_height Optional. Maximum wanted height.
357 * @return array First item is the width, the second item is the height.
359 function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
360 if ( !$max_width and !$max_height )
361 return array( $current_width, $current_height );
363 $width_ratio = $height_ratio = 1.0;
364 $did_width = $did_height = false;
366 if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
367 $width_ratio = $max_width / $current_width;
371 if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
372 $height_ratio = $max_height / $current_height;
376 // Calculate the larger/smaller ratios
377 $smaller_ratio = min( $width_ratio, $height_ratio );
378 $larger_ratio = max( $width_ratio, $height_ratio );
380 if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
381 // The larger ratio is too big. It would result in an overflow.
382 $ratio = $smaller_ratio;
384 // The larger ratio fits, and is likely to be a more "snug" fit.
385 $ratio = $larger_ratio;
387 // Very small dimensions may result in 0, 1 should be the minimum.
388 $w = max ( 1, intval( $current_width * $ratio ) );
389 $h = max ( 1, intval( $current_height * $ratio ) );
391 // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
392 // 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.
393 // Thus we look for dimensions that are one pixel shy of the max value and bump them up
394 if ( $did_width && $w == $max_width - 1 )
395 $w = $max_width; // Round it up
396 if ( $did_height && $h == $max_height - 1 )
397 $h = $max_height; // Round it up
399 return array( $w, $h );
403 * Retrieve calculated resize dimensions for use in WP_Image_Editor.
405 * Calculates dimensions and coordinates for a resized image that fits
406 * within a specified width and height.
408 * Cropping behavior is dependent on the value of $crop:
409 * 1. If false (default), images will not be cropped.
410 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
411 * - x_crop_position accepts 'left' 'center', or 'right'.
412 * - y_crop_position accepts 'top', 'center', or 'bottom'.
413 * Images will be cropped to the specified dimensions within the defined crop area.
414 * 3. If true, images will be cropped to the specified dimensions using center positions.
418 * @param int $orig_w Original width in pixels.
419 * @param int $orig_h Original height in pixels.
420 * @param int $dest_w New width in pixels.
421 * @param int $dest_h New height in pixels.
422 * @param bool|array $crop Optional. Whether to crop image to specified height and width or resize.
423 * An array can specify positioning of the crop area. Default false.
424 * @return bool|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
426 function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
428 if ($orig_w <= 0 || $orig_h <= 0)
430 // at least one of dest_w or dest_h must be specific
431 if ($dest_w <= 0 && $dest_h <= 0)
435 * Filter whether to preempt calculating the image resize dimensions.
437 * Passing a non-null value to the filter will effectively short-circuit
438 * image_resize_dimensions(), returning that value instead.
442 * @param null|mixed $null Whether to preempt output of the resize dimensions.
443 * @param int $orig_w Original width in pixels.
444 * @param int $orig_h Original height in pixels.
445 * @param int $dest_w New width in pixels.
446 * @param int $dest_h New height in pixels.
447 * @param bool|array $crop Whether to crop image to specified height and width or resize.
448 * An array can specify positioning of the crop area. Default false.
450 $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
451 if ( null !== $output )
455 // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
456 $aspect_ratio = $orig_w / $orig_h;
457 $new_w = min($dest_w, $orig_w);
458 $new_h = min($dest_h, $orig_h);
461 $new_w = intval($new_h * $aspect_ratio);
465 $new_h = intval($new_w / $aspect_ratio);
468 $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
470 $crop_w = round($new_w / $size_ratio);
471 $crop_h = round($new_h / $size_ratio);
473 if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
474 $crop = array( 'center', 'center' );
477 list( $x, $y ) = $crop;
479 if ( 'left' === $x ) {
481 } elseif ( 'right' === $x ) {
482 $s_x = $orig_w - $crop_w;
484 $s_x = floor( ( $orig_w - $crop_w ) / 2 );
487 if ( 'top' === $y ) {
489 } elseif ( 'bottom' === $y ) {
490 $s_y = $orig_h - $crop_h;
492 $s_y = floor( ( $orig_h - $crop_h ) / 2 );
495 // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
502 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
505 // if the resulting image would be the same size or larger we don't want to resize it
506 if ( $new_w >= $orig_w && $new_h >= $orig_h )
509 // the return array matches the parameters to imagecopyresampled()
510 // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
511 return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
516 * Resize an image to make a thumbnail or intermediate size.
518 * The returned array has the file size, the image width, and image height. The
519 * filter 'image_make_intermediate_size' can be used to hook in and change the
520 * values of the returned array. The only parameter is the resized file path.
524 * @param string $file File path.
525 * @param int $width Image width.
526 * @param int $height Image height.
527 * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
528 * @return bool|array False, if no image was created. Metadata array on success.
530 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
531 if ( $width || $height ) {
532 $editor = wp_get_image_editor( $file );
534 if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
537 $resized_file = $editor->save();
539 if ( ! is_wp_error( $resized_file ) && $resized_file ) {
540 unset( $resized_file['path'] );
541 return $resized_file;
548 * Retrieve the image's intermediate size (resized) path, width, and height.
550 * The $size parameter can be an array with the width and height respectively.
551 * If the size matches the 'sizes' metadata array for width and height, then it
552 * will be used. If there is no direct match, then the nearest image size larger
553 * than the specified size will be used. If nothing is found, then the function
554 * will break out and return false.
556 * The metadata 'sizes' is used for compatible sizes that can be used for the
557 * parameter $size value.
559 * The url path will be given, when the $size parameter is a string.
561 * If you are passing an array for the $size, you should consider using
562 * add_image_size() so that a cropped version is generated. It's much more
563 * efficient than having to find the closest-sized image and then having the
564 * browser scale down the image.
567 * @see add_image_size()
569 * @param int $post_id Attachment ID for image.
570 * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
571 * @return bool|array False on failure or array of file path, width, and height on success.
573 function image_get_intermediate_size($post_id, $size='thumbnail') {
574 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
577 // get the best one for a specified set of dimensions
578 if ( is_array($size) && !empty($imagedata['sizes']) ) {
579 foreach ( $imagedata['sizes'] as $_size => $data ) {
580 // already cropped to width or height; so use this size
581 if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
582 $file = $data['file'];
583 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
584 return compact( 'file', 'width', 'height' );
586 // add to lookup table: area => size
587 $areas[$data['width'] * $data['height']] = $_size;
589 if ( !$size || !empty($areas) ) {
590 // find for the smallest image not smaller than the desired size
592 foreach ( $areas as $_size ) {
593 $data = $imagedata['sizes'][$_size];
594 if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
595 // Skip images with unexpectedly divergent aspect ratios (crops)
596 // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
597 $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
598 // 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
599 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'] ) ) )
601 // If we're still here, then we're going to use this size
602 $file = $data['file'];
603 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
604 return compact( 'file', 'width', 'height' );
610 if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
613 $data = $imagedata['sizes'][$size];
614 // include the full filesystem path of the intermediate file
615 if ( empty($data['path']) && !empty($data['file']) ) {
616 $file_url = wp_get_attachment_url($post_id);
617 $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
618 $data['url'] = path_join( dirname($file_url), $data['file'] );
624 * Get the available image sizes
626 * @return array Returns a filtered array of image size strings
628 function get_intermediate_image_sizes() {
629 global $_wp_additional_image_sizes;
630 $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
631 if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
632 $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
635 * Filter the list of intermediate image sizes.
639 * @param array $image_sizes An array of intermediate image sizes. Defaults
640 * are 'thumbnail', 'medium', 'large'.
642 return apply_filters( 'intermediate_image_sizes', $image_sizes );
646 * Retrieve an image to represent an attachment.
648 * A mime icon for files, thumbnail or intermediate size for images.
652 * @param int $attachment_id Image attachment ID.
653 * @param string $size Optional, default is 'thumbnail'.
654 * @param bool $icon Optional, default is false. Whether it is an icon.
655 * @return bool|array Returns an array (url, width, height), or false, if no image is available.
657 function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
659 // get a thumbnail or intermediate image if there is one
660 if ( $image = image_downsize($attachment_id, $size) )
665 if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
666 /** This filter is documented in wp-includes/post.php */
667 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
668 $src_file = $icon_dir . '/' . wp_basename($src);
669 @list($width, $height) = getimagesize($src_file);
671 if ( $src && $width && $height )
672 return array( $src, $width, $height );
677 * Get an HTML img element representing an image attachment
679 * While $size will accept an array, it is better to register a size with
680 * add_image_size() so that a cropped version is generated. It's much more
681 * efficient than having to find the closest-sized image and then having the
682 * browser scale down the image.
686 * @see add_image_size()
687 * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
689 * @param int $attachment_id Image attachment ID.
690 * @param string $size Optional, default is 'thumbnail'.
691 * @param bool $icon Optional, default is false. Whether it is an icon.
692 * @param mixed $attr Optional, attributes for the image markup.
693 * @return string HTML img element or empty string on failure.
695 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
698 $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
700 list($src, $width, $height) = $image;
701 $hwstring = image_hwstring($width, $height);
702 if ( is_array($size) )
703 $size = join('x', $size);
704 $attachment = get_post($attachment_id);
705 $default_attr = array(
707 'class' => "attachment-$size",
708 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
710 if ( empty($default_attr['alt']) )
711 $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
712 if ( empty($default_attr['alt']) )
713 $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
715 $attr = wp_parse_args($attr, $default_attr);
718 * Filter the list of attachment image attributes.
722 * @param mixed $attr Attributes for the image markup.
723 * @param int $attachment_id Image attachment ID.
725 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
726 $attr = array_map( 'esc_attr', $attr );
727 $html = rtrim("<img $hwstring");
728 foreach ( $attr as $name => $value ) {
729 $html .= " $name=" . '"' . $value . '"';
738 * Adds a 'wp-post-image' class to post thumbnails
739 * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
740 * dynamically add/remove itself so as to only filter post thumbnails
743 * @param array $attr Attributes including src, class, alt, title
746 function _wp_post_thumbnail_class_filter( $attr ) {
747 $attr['class'] .= ' wp-post-image';
752 * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
756 function _wp_post_thumbnail_class_filter_add( $attr ) {
757 add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
761 * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
765 function _wp_post_thumbnail_class_filter_remove( $attr ) {
766 remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
769 add_shortcode('wp_caption', 'img_caption_shortcode');
770 add_shortcode('caption', 'img_caption_shortcode');
773 * The Caption shortcode.
775 * Allows a plugin to replace the content that would otherwise be returned. The
776 * filter is 'img_caption_shortcode' and passes an empty string, the attr
777 * parameter and the content parameter values.
779 * The supported attributes for the shortcode are 'id', 'align', 'width', and
784 * @param array $attr {
785 * Attributes of the caption shortcode.
787 * @type string $id ID of the div element for the caption.
788 * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
789 * 'aligncenter', alignright', 'alignnone'.
790 * @type int $width The width of the caption, in pixels.
791 * @type string $caption The caption text.
792 * @type string $class Additional class name(s) added to the caption container.
794 * @param string $content Optional. Shortcode content.
795 * @return string HTML content to display the caption.
797 function img_caption_shortcode( $attr, $content = null ) {
798 // New-style shortcode with the caption inside the shortcode with the link and image tags.
799 if ( ! isset( $attr['caption'] ) ) {
800 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
801 $content = $matches[1];
802 $attr['caption'] = trim( $matches[2] );
807 * Filter the default caption shortcode output.
809 * If the filtered output isn't empty, it will be used instead of generating
810 * the default caption template.
814 * @see img_caption_shortcode()
816 * @param string $output The caption output. Default empty.
817 * @param array $attr Attributes of the caption shortcode.
818 * @param string $content The image element, possibly wrapped in a hyperlink.
820 $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
824 $atts = shortcode_atts( array(
826 'align' => 'alignnone',
830 ), $attr, 'caption' );
832 $atts['width'] = (int) $atts['width'];
833 if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
836 if ( ! empty( $atts['id'] ) )
837 $atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';
839 $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
841 if ( current_theme_supports( 'html5', 'caption' ) ) {
842 return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
843 . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
846 $caption_width = 10 + $atts['width'];
849 * Filter the width of an image's caption.
851 * By default, the caption is 10 pixels greater than the width of the image,
852 * to prevent post content from running up against a floated image.
856 * @see img_caption_shortcode()
858 * @param int $caption_width Width of the caption in pixels. To remove this inline style,
860 * @param array $atts Attributes of the caption shortcode.
861 * @param string $content The image element, possibly wrapped in a hyperlink.
863 $caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
866 if ( $caption_width )
867 $style = 'style="width: ' . (int) $caption_width . 'px" ';
869 return '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
870 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
873 add_shortcode('gallery', 'gallery_shortcode');
876 * The Gallery shortcode.
878 * This implements the functionality of the Gallery Shortcode for displaying
879 * WordPress images on a post.
883 * @param array $attr {
884 * Attributes of the gallery shortcode.
886 * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
887 * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
888 * Accepts any valid SQL ORDERBY statement.
889 * @type int $id Post ID.
890 * @type string $itemtag HTML tag to use for each image in the gallery.
891 * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
892 * @type string $icontag HTML tag to use for each image's icon.
893 * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
894 * @type string $captiontag HTML tag to use for each image's caption.
895 * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
896 * @type int $columns Number of columns of images to display. Default 3.
897 * @type string $size Size of the images to display. Default 'thumbnail'.
898 * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
899 * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
900 * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
901 * @type string $link What to link each image to. Default empty (links to the attachment page).
902 * Accepts 'file', 'none'.
904 * @return string HTML content to display gallery.
906 function gallery_shortcode( $attr ) {
909 static $instance = 0;
912 if ( ! empty( $attr['ids'] ) ) {
913 // 'ids' is explicitly ordered, unless you specify otherwise.
914 if ( empty( $attr['orderby'] ) )
915 $attr['orderby'] = 'post__in';
916 $attr['include'] = $attr['ids'];
920 * Filter the default gallery shortcode output.
922 * If the filtered output isn't empty, it will be used instead of generating
923 * the default gallery template.
927 * @see gallery_shortcode()
929 * @param string $output The gallery output. Default empty.
930 * @param array $attr Attributes of the gallery shortcode.
932 $output = apply_filters( 'post_gallery', '', $attr );
936 // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
937 if ( isset( $attr['orderby'] ) ) {
938 $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
939 if ( !$attr['orderby'] )
940 unset( $attr['orderby'] );
943 $html5 = current_theme_supports( 'html5', 'gallery' );
944 extract(shortcode_atts(array(
946 'orderby' => 'menu_order ID',
947 'id' => $post ? $post->ID : 0,
948 'itemtag' => $html5 ? 'figure' : 'dl',
949 'icontag' => $html5 ? 'div' : 'dt',
950 'captiontag' => $html5 ? 'figcaption' : 'dd',
952 'size' => 'thumbnail',
956 ), $attr, 'gallery'));
959 if ( 'RAND' == $order )
962 if ( !empty($include) ) {
963 $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
965 $attachments = array();
966 foreach ( $_attachments as $key => $val ) {
967 $attachments[$val->ID] = $_attachments[$key];
969 } elseif ( !empty($exclude) ) {
970 $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
972 $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
975 if ( empty($attachments) )
980 foreach ( $attachments as $att_id => $attachment )
981 $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
985 $itemtag = tag_escape($itemtag);
986 $captiontag = tag_escape($captiontag);
987 $icontag = tag_escape($icontag);
988 $valid_tags = wp_kses_allowed_html( 'post' );
989 if ( ! isset( $valid_tags[ $itemtag ] ) )
991 if ( ! isset( $valid_tags[ $captiontag ] ) )
993 if ( ! isset( $valid_tags[ $icontag ] ) )
996 $columns = intval($columns);
997 $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
998 $float = is_rtl() ? 'right' : 'left';
1000 $selector = "gallery-{$instance}";
1002 $gallery_style = $gallery_div = '';
1005 * Filter whether to print default gallery styles.
1009 * @param bool $print Whether to print default gallery styles.
1010 * Defaults to false if the theme supports HTML5 galleries.
1011 * Otherwise, defaults to true.
1013 if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1015 <style type='text/css'>
1019 #{$selector} .gallery-item {
1023 width: {$itemwidth}%;
1026 border: 2px solid #cfcfcf;
1028 #{$selector} .gallery-caption {
1031 /* see gallery_shortcode() in wp-includes/media.php */
1035 $size_class = sanitize_html_class( $size );
1036 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1039 * Filter the default gallery shortcode CSS styles.
1043 * @param string $gallery_style Default gallery shortcode CSS styles.
1044 * @param string $gallery_div Opening HTML div container for the gallery shortcode output.
1046 $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1049 foreach ( $attachments as $id => $attachment ) {
1050 if ( ! empty( $link ) && 'file' === $link )
1051 $image_output = wp_get_attachment_link( $id, $size, false, false );
1052 elseif ( ! empty( $link ) && 'none' === $link )
1053 $image_output = wp_get_attachment_image( $id, $size, false );
1055 $image_output = wp_get_attachment_link( $id, $size, true, false );
1057 $image_meta = wp_get_attachment_metadata( $id );
1060 if ( isset( $image_meta['height'], $image_meta['width'] ) )
1061 $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1063 $output .= "<{$itemtag} class='gallery-item'>";
1065 <{$icontag} class='gallery-icon {$orientation}'>
1068 if ( $captiontag && trim($attachment->post_excerpt) ) {
1070 <{$captiontag} class='wp-caption-text gallery-caption'>
1071 " . wptexturize($attachment->post_excerpt) . "
1074 $output .= "</{$itemtag}>";
1075 if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1076 $output .= '<br style="clear: both" />';
1080 if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1082 <br style='clear: both' />";
1092 * Output the templates used by playlists.
1096 function wp_underscore_playlist_templates() {
1098 <script type="text/html" id="tmpl-wp-playlist-current-item">
1099 <# if ( data.image ) { #>
1100 <img src="{{ data.thumb.src }}"/>
1102 <div class="wp-playlist-caption">
1103 <span class="wp-playlist-item-meta wp-playlist-item-title">“{{ data.title }}”</span>
1104 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1105 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1108 <script type="text/html" id="tmpl-wp-playlist-item">
1109 <div class="wp-playlist-item">
1110 <a class="wp-playlist-caption" href="{{ data.src }}">
1111 {{ data.index ? ( data.index + '. ' ) : '' }}
1112 <# if ( data.caption ) { #>
1115 <span class="wp-playlist-item-title">“{{{ data.title }}}”</span>
1116 <# if ( data.artists && data.meta.artist ) { #>
1117 <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span>
1121 <# if ( data.meta.length_formatted ) { #>
1122 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1130 * Output and enqueue default scripts and styles for playlists.
1134 * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1136 function wp_playlist_scripts( $type ) {
1137 wp_enqueue_style( 'wp-mediaelement' );
1138 wp_enqueue_script( 'wp-playlist' );
1140 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1142 add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1143 add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1145 add_action( 'wp_playlist_scripts', 'wp_playlist_scripts' );
1148 * The playlist shortcode.
1150 * This implements the functionality of the playlist shortcode for displaying
1151 * a collection of WordPress audio or video files in a post.
1155 * @param array $attr Playlist shortcode attributes.
1156 * @return string Playlist output. Empty string if the passed type is unsupported.
1158 function wp_playlist_shortcode( $attr ) {
1159 global $content_width;
1162 static $instance = 0;
1165 if ( ! empty( $attr['ids'] ) ) {
1166 // 'ids' is explicitly ordered, unless you specify otherwise.
1167 if ( empty( $attr['orderby'] ) ) {
1168 $attr['orderby'] = 'post__in';
1170 $attr['include'] = $attr['ids'];
1174 * Filter the playlist output.
1176 * Passing a non-empty value to the filter will short-circuit generation
1177 * of the default playlist output, returning the passed value instead.
1181 * @param string $output Playlist output. Default empty.
1182 * @param array $attr An array of shortcode attributes.
1184 $output = apply_filters( 'post_playlist', '', $attr );
1185 if ( $output != '' ) {
1190 * We're trusting author input, so let's at least make sure it looks
1191 * like a valid orderby statement.
1193 if ( isset( $attr['orderby'] ) ) {
1194 $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
1195 if ( ! $attr['orderby'] )
1196 unset( $attr['orderby'] );
1199 extract( shortcode_atts( array(
1202 'orderby' => 'menu_order ID',
1203 'id' => $post ? $post->ID : 0,
1207 'tracklist' => true,
1208 'tracknumbers' => true,
1211 ), $attr, 'playlist' ) );
1213 $id = intval( $id );
1214 if ( 'RAND' == $order ) {
1219 'post_status' => 'inherit',
1220 'post_type' => 'attachment',
1221 'post_mime_type' => $type,
1223 'orderby' => $orderby
1226 if ( ! empty( $include ) ) {
1227 $args['include'] = $include;
1228 $_attachments = get_posts( $args );
1230 $attachments = array();
1231 foreach ( $_attachments as $key => $val ) {
1232 $attachments[$val->ID] = $_attachments[$key];
1234 } elseif ( ! empty( $exclude ) ) {
1235 $args['post_parent'] = $id;
1236 $args['exclude'] = $exclude;
1237 $attachments = get_children( $args );
1239 $args['post_parent'] = $id;
1240 $attachments = get_children( $args );
1243 if ( empty( $attachments ) ) {
1249 foreach ( $attachments as $att_id => $attachment ) {
1250 $output .= wp_get_attachment_link( $att_id ) . "\n";
1255 $outer = 22; // default padding and border of wrapper
1257 $default_width = 640;
1258 $default_height = 360;
1260 $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
1261 $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
1263 $data = compact( 'type' );
1265 // don't pass strings to JSON, will be truthy in JS
1266 foreach ( array( 'tracklist', 'tracknumbers', 'images', 'artists' ) as $key ) {
1267 $data[$key] = filter_var( $$key, FILTER_VALIDATE_BOOLEAN );
1271 foreach ( $attachments as $attachment ) {
1272 $url = wp_get_attachment_url( $attachment->ID );
1273 $ftype = wp_check_filetype( $url, wp_get_mime_types() );
1276 'type' => $ftype['type'],
1277 'title' => $attachment->post_title,
1278 'caption' => $attachment->post_excerpt,
1279 'description' => $attachment->post_content
1282 $track['meta'] = array();
1283 $meta = wp_get_attachment_metadata( $attachment->ID );
1284 if ( ! empty( $meta ) ) {
1286 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
1287 if ( ! empty( $meta[ $key ] ) ) {
1288 $track['meta'][ $key ] = $meta[ $key ];
1292 if ( 'video' === $type ) {
1293 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1294 $width = $meta['width'];
1295 $height = $meta['height'];
1296 $theme_height = round( ( $height * $theme_width ) / $width );
1298 $width = $default_width;
1299 $height = $default_height;
1302 $track['dimensions'] = array(
1303 'original' => compact( 'width', 'height' ),
1305 'width' => $theme_width,
1306 'height' => $theme_height
1313 $id = get_post_thumbnail_id( $attachment->ID );
1314 if ( ! empty( $id ) ) {
1315 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
1316 $track['image'] = compact( 'src', 'width', 'height' );
1317 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
1318 $track['thumb'] = compact( 'src', 'width', 'height' );
1320 $src = wp_mime_type_icon( $attachment->ID );
1323 $track['image'] = compact( 'src', 'width', 'height' );
1324 $track['thumb'] = compact( 'src', 'width', 'height' );
1330 $data['tracks'] = $tracks;
1332 $safe_type = esc_attr( $type );
1333 $safe_style = esc_attr( $style );
1337 if ( 1 === $instance ) {
1339 * Print and enqueue playlist scripts, styles, and JavaScript templates.
1343 * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
1344 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
1346 do_action( 'wp_playlist_scripts', $type, $style );
1348 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
1349 <?php if ( 'audio' === $type ): ?>
1350 <div class="wp-playlist-current-item"></div>
1352 <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
1353 echo (int) $theme_width;
1354 ?>"<?php if ( 'video' === $safe_type ):
1355 echo ' height="', (int) $theme_height, '"';
1357 echo ' style="visibility: hidden"';
1358 endif; ?>></<?php echo $safe_type ?>>
1359 <div class="wp-playlist-next"></div>
1360 <div class="wp-playlist-prev"></div>
1363 foreach ( $attachments as $att_id => $attachment ) {
1364 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
1368 <script type="application/json"><?php echo json_encode( $data ) ?></script>
1371 return ob_get_clean();
1373 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
1376 * Provide a No-JS Flash fallback as a last resort for audio / video
1380 * @param string $url
1381 * @return string Fallback HTML
1383 function wp_mediaelement_fallback( $url ) {
1385 * Filter the Mediaelement fallback output for no-JS.
1389 * @param string $output Fallback output for no-JS.
1390 * @param string $url Media file URL.
1392 return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
1396 * Return a filtered list of WP-supported audio formats.
1401 function wp_get_audio_extensions() {
1403 * Filter the list of supported audio formats.
1407 * @param array $extensions An array of support audio formats. Defaults are
1408 * 'mp3', 'ogg', 'wma', 'm4a', 'wav'.
1410 return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
1414 * Return useful keys to use to lookup data from an attachment's stored metadata.
1418 * @param WP_Post $attachment The current attachment, provided for context.
1419 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
1420 * @return array Key/value pairs of field keys to labels.
1422 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
1424 'artist' => __( 'Artist' ),
1425 'album' => __( 'Album' ),
1428 if ( 'display' === $context ) {
1429 $fields['genre'] = __( 'Genre' );
1430 $fields['year'] = __( 'Year' );
1431 $fields['length_formatted'] = _x( 'Length', 'video or audio' );
1435 * Filter the editable list of keys to look up data from an attachment's metadata.
1439 * @param array $fields Key/value pairs of field keys to labels.
1440 * @param WP_Post $attachment Attachment object.
1441 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
1443 return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
1446 * The Audio shortcode.
1448 * This implements the functionality of the Audio Shortcode for displaying
1449 * WordPress mp3s in a post.
1453 * @param array $attr {
1454 * Attributes of the audio shortcode.
1456 * @type string $src URL to the source of the audio file. Default empty.
1457 * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
1458 * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
1459 * @type string $preload The 'preload' attribute for the `<audio>` element. Default empty.
1460 * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
1461 * @type string $id The 'id' attribute for the `<audio>` element. Default 'audio-{$post_id}-{$instances}'.
1462 * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
1464 * @param string $content Optional. Shortcode content.
1465 * @return string HTML content to display audio.
1467 function wp_audio_shortcode( $attr, $content = '' ) {
1468 $post_id = get_post() ? get_the_ID() : 0;
1470 static $instances = 0;
1474 * Filter the default audio shortcode output.
1476 * If the filtered output isn't empty, it will be used instead of generating the default audio template.
1480 * @param string $html Empty variable to be replaced with shortcode markup.
1481 * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
1482 * @param string $content Shortcode content.
1483 * @param int $instances Unique numeric ID of this audio shortcode instance.
1485 $html = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instances );
1491 $default_types = wp_get_audio_extensions();
1492 $defaults_atts = array(
1498 foreach ( $default_types as $type )
1499 $defaults_atts[$type] = '';
1501 $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
1505 if ( ! empty( $src ) ) {
1506 $type = wp_check_filetype( $src, wp_get_mime_types() );
1507 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) )
1508 return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
1510 array_unshift( $default_types, 'src' );
1512 foreach ( $default_types as $ext ) {
1513 if ( ! empty( $$ext ) ) {
1514 $type = wp_check_filetype( $$ext, wp_get_mime_types() );
1515 if ( strtolower( $type['ext'] ) === $ext )
1522 $audios = get_attached_media( 'audio', $post_id );
1523 if ( empty( $audios ) )
1526 $audio = reset( $audios );
1527 $src = wp_get_attachment_url( $audio->ID );
1528 if ( empty( $src ) )
1531 array_unshift( $default_types, 'src' );
1535 * Filter the media library used for the audio shortcode.
1539 * @param string $library Media library used for the audio shortcode.
1541 $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
1542 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1543 wp_enqueue_style( 'wp-mediaelement' );
1544 wp_enqueue_script( 'wp-mediaelement' );
1548 * Filter the class attribute for the audio shortcode output container.
1552 * @param string $class CSS class or list of space-separated classes.
1555 'class' => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
1556 'id' => sprintf( 'audio-%d-%d', $post_id, $instances ),
1558 'autoplay' => $autoplay,
1559 'preload' => $preload,
1560 'style' => 'width: 100%; visibility: hidden;',
1563 // These ones should just be omitted altogether if they are blank
1564 foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
1565 if ( empty( $atts[$a] ) )
1569 $attr_strings = array();
1570 foreach ( $atts as $k => $v ) {
1571 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1575 if ( 'mediaelement' === $library && 1 === $instances )
1576 $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
1577 $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
1580 $source = '<source type="%s" src="%s" />';
1581 foreach ( $default_types as $fallback ) {
1582 if ( ! empty( $$fallback ) ) {
1583 if ( empty( $fileurl ) )
1584 $fileurl = $$fallback;
1585 $type = wp_check_filetype( $$fallback, wp_get_mime_types() );
1586 $url = add_query_arg( '_', $instances, $$fallback );
1587 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1591 if ( 'mediaelement' === $library )
1592 $html .= wp_mediaelement_fallback( $fileurl );
1593 $html .= '</audio>';
1596 * Filter the audio shortcode output.
1600 * @param string $html Audio shortcode HTML output.
1601 * @param array $atts Array of audio shortcode attributes.
1602 * @param string $audio Audio file.
1603 * @param int $post_id Post ID.
1604 * @param string $library Media library used for the audio shortcode.
1606 return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
1608 add_shortcode( 'audio', 'wp_audio_shortcode' );
1611 * Return a filtered list of WP-supported video formats
1616 function wp_get_video_extensions() {
1618 * Filter the list of supported video formats.
1622 * @param array $extensions An array of support video formats. Defaults are
1623 * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
1625 return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
1629 * The Video shortcode.
1631 * This implements the functionality of the Video Shortcode for displaying
1632 * WordPress mp4s in a post.
1636 * @param array $attr {
1637 * Attributes of the shortcode.
1639 * @type string $src URL to the source of the video file. Default empty.
1640 * @type int $height Height of the video embed in pixels. Default 360.
1641 * @type int $width Width of the video embed in pixels. Default $content_width or 640.
1642 * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
1643 * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
1644 * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
1645 * @type string $preload The 'preload' attribute for the `<video>` element.
1646 * Default 'metadata'.
1647 * @type string $class The 'class' attribute for the `<video>` element.
1648 * Default 'wp-video-shortcode'.
1649 * @type string $id The 'id' attribute for the `<video>` element.
1650 * Default 'video-{$post_id}-{$instances}'.
1652 * @param string $content Optional. Shortcode content.
1653 * @return string HTML content to display video.
1655 function wp_video_shortcode( $attr, $content = '' ) {
1656 global $content_width;
1657 $post_id = get_post() ? get_the_ID() : 0;
1659 static $instances = 0;
1663 * Filter the default video shortcode output.
1665 * If the filtered output isn't empty, it will be used instead of generating
1666 * the default video template.
1670 * @see wp_video_shortcode()
1672 * @param string $html Empty variable to be replaced with shortcode markup.
1673 * @param array $attr Attributes of the video shortcode.
1674 * @param string $content Video shortcode content.
1675 * @param int $instances Unique numeric ID of this video shortcode instance.
1677 $html = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instances );
1683 $default_types = wp_get_video_extensions();
1684 $defaults_atts = array(
1689 'preload' => 'metadata',
1694 foreach ( $default_types as $type )
1695 $defaults_atts[$type] = '';
1697 $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
1701 // shrink the video so it isn't huge in the admin
1702 if ( $width > $defaults_atts['width'] ) {
1703 $height = round( ( $height * $defaults_atts['width'] ) / $width );
1704 $width = $defaults_atts['width'];
1707 // if the video is bigger than the theme
1708 if ( ! empty( $content_width ) && $width > $content_width ) {
1709 $height = round( ( $height * $content_width ) / $width );
1710 $width = $content_width;
1714 $yt_pattern = '#^https?://(:?www\.)?(:?youtube\.com/watch|youtu\.be/)#';
1717 if ( ! empty( $src ) ) {
1718 if ( ! preg_match( $yt_pattern, $src ) ) {
1719 $type = wp_check_filetype( $src, wp_get_mime_types() );
1720 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
1721 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
1725 array_unshift( $default_types, 'src' );
1727 foreach ( $default_types as $ext ) {
1728 if ( ! empty( $$ext ) ) {
1729 $type = wp_check_filetype( $$ext, wp_get_mime_types() );
1730 if ( strtolower( $type['ext'] ) === $ext )
1737 $videos = get_attached_media( 'video', $post_id );
1738 if ( empty( $videos ) )
1741 $video = reset( $videos );
1742 $src = wp_get_attachment_url( $video->ID );
1743 if ( empty( $src ) )
1746 array_unshift( $default_types, 'src' );
1750 * Filter the media library used for the video shortcode.
1754 * @param string $library Media library used for the video shortcode.
1756 $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
1757 if ( 'mediaelement' === $library && did_action( 'init' ) ) {
1758 wp_enqueue_style( 'wp-mediaelement' );
1759 wp_enqueue_script( 'wp-mediaelement' );
1763 * Filter the class attribute for the video shortcode output container.
1767 * @param string $class CSS class or list of space-separated classes.
1770 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
1771 'id' => sprintf( 'video-%d-%d', $post_id, $instances ),
1772 'width' => absint( $width ),
1773 'height' => absint( $height ),
1774 'poster' => esc_url( $poster ),
1776 'autoplay' => $autoplay,
1777 'preload' => $preload,
1780 // These ones should just be omitted altogether if they are blank
1781 foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
1782 if ( empty( $atts[$a] ) )
1786 $attr_strings = array();
1787 foreach ( $atts as $k => $v ) {
1788 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
1792 if ( 'mediaelement' === $library && 1 === $instances )
1793 $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
1794 $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
1797 $source = '<source type="%s" src="%s" />';
1798 foreach ( $default_types as $fallback ) {
1799 if ( ! empty( $$fallback ) ) {
1800 if ( empty( $fileurl ) )
1801 $fileurl = $$fallback;
1803 if ( 'src' === $fallback && preg_match( $yt_pattern, $src ) ) {
1804 $type = array( 'type' => 'video/youtube' );
1806 $type = wp_check_filetype( $$fallback, wp_get_mime_types() );
1808 $url = add_query_arg( '_', $instances, $$fallback );
1809 $html .= sprintf( $source, $type['type'], esc_url( $url ) );
1813 if ( ! empty( $content ) ) {
1814 if ( false !== strpos( $content, "\n" ) )
1815 $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
1817 $html .= trim( $content );
1820 if ( 'mediaelement' === $library )
1821 $html .= wp_mediaelement_fallback( $fileurl );
1822 $html .= '</video>';
1824 $html = sprintf( '<div style="width: %dpx; max-width: 100%%;" class="wp-video">%s</div>', $width, $html );
1827 * Filter the output of the video shortcode.
1831 * @param string $html Video shortcode HTML output.
1832 * @param array $atts Array of video shortcode attributes.
1833 * @param string $video Video file.
1834 * @param int $post_id Post ID.
1835 * @param string $library Media library used for the video shortcode.
1837 return apply_filters( 'wp_video_shortcode', $html, $atts, $video, $post_id, $library );
1839 add_shortcode( 'video', 'wp_video_shortcode' );
1842 * Display previous image link that has the same post parent.
1845 * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
1846 * @param string $text Optional, default is false. If included, link will reflect $text variable.
1847 * @return string HTML content.
1849 function previous_image_link($size = 'thumbnail', $text = false) {
1850 adjacent_image_link(true, $size, $text);
1854 * Display next image link that has the same post parent.
1857 * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
1858 * @param string $text Optional, default is false. If included, link will reflect $text variable.
1859 * @return string HTML content.
1861 function next_image_link($size = 'thumbnail', $text = false) {
1862 adjacent_image_link(false, $size, $text);
1866 * Display next or previous image link that has the same post parent.
1868 * Retrieves the current attachment object from the $post global.
1872 * @param bool $prev Optional. Default is true to display previous link, false for next.
1874 function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
1876 $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' ) ) );
1878 foreach ( $attachments as $k => $attachment )
1879 if ( $attachment->ID == $post->ID )
1882 $k = $prev ? $k - 1 : $k + 1;
1884 $output = $attachment_id = null;
1885 if ( isset( $attachments[ $k ] ) ) {
1886 $attachment_id = $attachments[ $k ]->ID;
1887 $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
1890 $adjacent = $prev ? 'previous' : 'next';
1893 * Filter the adjacent image link.
1895 * The dynamic portion of the hook name, $adjacent, refers to the type of adjacency,
1896 * either 'next', or 'previous'.
1900 * @param string $output Adjacent image HTML markup.
1901 * @param int $attachment_id Attachment ID
1902 * @param string $size Image size.
1903 * @param string $text Link text.
1905 echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
1909 * Retrieve taxonomies attached to the attachment.
1913 * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
1914 * @return array Empty array on failure. List of taxonomies on success.
1916 function get_attachment_taxonomies($attachment) {
1917 if ( is_int( $attachment ) )
1918 $attachment = get_post($attachment);
1919 else if ( is_array($attachment) )
1920 $attachment = (object) $attachment;
1922 if ( ! is_object($attachment) )
1925 $filename = basename($attachment->guid);
1927 $objects = array('attachment');
1929 if ( false !== strpos($filename, '.') )
1930 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
1931 if ( !empty($attachment->post_mime_type) ) {
1932 $objects[] = 'attachment:' . $attachment->post_mime_type;
1933 if ( false !== strpos($attachment->post_mime_type, '/') )
1934 foreach ( explode('/', $attachment->post_mime_type) as $token )
1935 if ( !empty($token) )
1936 $objects[] = "attachment:$token";
1939 $taxonomies = array();
1940 foreach ( $objects as $object )
1941 if ( $taxes = get_object_taxonomies($object) )
1942 $taxonomies = array_merge($taxonomies, $taxes);
1944 return array_unique($taxonomies);
1948 * Return all of the taxonomy names that are registered for attachments.
1950 * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
1953 * @see get_attachment_taxonomies()
1954 * @uses get_taxonomies()
1956 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
1957 * @return array The names of all taxonomy of $object_type.
1959 function get_taxonomies_for_attachments( $output = 'names' ) {
1960 $taxonomies = array();
1961 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
1962 foreach ( $taxonomy->object_type as $object_type ) {
1963 if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
1964 if ( 'names' == $output )
1965 $taxonomies[] = $taxonomy->name;
1967 $taxonomies[ $taxonomy->name ] = $taxonomy;
1977 * Create new GD image resource with transparency support
1978 * @TODO: Deprecate if possible.
1982 * @param int $width Image width
1983 * @param int $height Image height
1984 * @return image resource
1986 function wp_imagecreatetruecolor($width, $height) {
1987 $img = imagecreatetruecolor($width, $height);
1988 if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
1989 imagealphablending($img, false);
1990 imagesavealpha($img, true);
1996 * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
1999 * @see WP_Embed::register_handler()
2001 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
2003 $wp_embed->register_handler( $id, $regex, $callback, $priority );
2007 * Unregister a previously registered embed handler.
2010 * @see WP_Embed::unregister_handler()
2012 function wp_embed_unregister_handler( $id, $priority = 10 ) {
2014 $wp_embed->unregister_handler( $id, $priority );
2018 * Create default array of embed parameters.
2020 * The width defaults to the content width as specified by the theme. If the
2021 * theme does not specify a content width, then 500px is used.
2023 * The default height is 1.5 times the width, or 1000px, whichever is smaller.
2025 * The 'embed_defaults' filter can be used to adjust either of these values.
2029 * @return array Default embed parameters.
2031 function wp_embed_defaults() {
2032 if ( ! empty( $GLOBALS['content_width'] ) )
2033 $width = (int) $GLOBALS['content_width'];
2035 if ( empty( $width ) )
2038 $height = min( ceil( $width * 1.5 ), 1000 );
2041 * Filter the default array of embed dimensions.
2045 * @param int $width Width of the embed in pixels.
2046 * @param int $height Height of the embed in pixels.
2048 return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
2052 * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
2055 * @uses wp_constrain_dimensions() This function passes the widths and the heights.
2057 * @param int $example_width The width of an example embed.
2058 * @param int $example_height The height of an example embed.
2059 * @param int $max_width The maximum allowed width.
2060 * @param int $max_height The maximum allowed height.
2061 * @return array The maximum possible width and height based on the example ratio.
2063 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
2064 $example_width = (int) $example_width;
2065 $example_height = (int) $example_height;
2066 $max_width = (int) $max_width;
2067 $max_height = (int) $max_height;
2069 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
2073 * Attempts to fetch the embed HTML for a provided URL using oEmbed.
2078 * @uses _wp_oembed_get_object()
2079 * @uses WP_oEmbed::get_html()
2081 * @param string $url The URL that should be embedded.
2082 * @param array $args Additional arguments and parameters.
2083 * @return bool|string False on failure or the embed HTML on success.
2085 function wp_oembed_get( $url, $args = '' ) {
2086 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2087 $oembed = _wp_oembed_get_object();
2088 return $oembed->get_html( $url, $args );
2092 * Adds a URL format and oEmbed provider URL pair.
2097 * @uses _wp_oembed_get_object()
2099 * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
2100 * @param string $provider The URL to the oEmbed provider.
2101 * @param boolean $regex Whether the $format parameter is in a regex format.
2103 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
2104 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2105 $oembed = _wp_oembed_get_object();
2106 $oembed->providers[$format] = array( $provider, $regex );
2110 * Removes an oEmbed provider.
2115 * @uses _wp_oembed_get_object()
2117 * @param string $format The URL format for the oEmbed provider to remove.
2119 function wp_oembed_remove_provider( $format ) {
2120 require_once( ABSPATH . WPINC . '/class-oembed.php' );
2122 $oembed = _wp_oembed_get_object();
2124 if ( isset( $oembed->providers[ $format ] ) ) {
2125 unset( $oembed->providers[ $format ] );
2133 * Determines if default embed handlers should be loaded.
2135 * Checks to make sure that the embeds library hasn't already been loaded. If
2136 * it hasn't, then it will load the embeds library.
2140 function wp_maybe_load_embeds() {
2142 * Filter whether to load the default embed handlers.
2144 * Returning a falsey value will prevent loading the default embed handlers.
2148 * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
2150 if ( ! apply_filters( 'load_default_embeds', true ) ) {
2154 wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
2157 * Filter the audio embed handler callback.
2161 * @param callback $handler Audio embed handler callback function.
2163 wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
2166 * Filter the video embed handler callback.
2170 * @param callback $handler Video embed handler callback function.
2172 wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
2176 * The Google Video embed handler callback. Google Video does not support oEmbed.
2178 * @see WP_Embed::register_handler()
2179 * @see WP_Embed::shortcode()
2181 * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
2182 * @param array $attr Embed attributes.
2183 * @param string $url The original URL that was matched by the regex.
2184 * @param array $rawattr The original unmodified attributes.
2185 * @return string The embed HTML.
2187 function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
2188 // If the user supplied a fixed width AND height, use it
2189 if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
2190 $width = (int) $rawattr['width'];
2191 $height = (int) $rawattr['height'];
2193 list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
2197 * Filter the Google Video embed output.
2201 * @param string $html Google Video HTML embed markup.
2202 * @param array $matches The regex matches from the provided regex.
2203 * @param array $attr An array of embed attributes.
2204 * @param string $url The original URL that was matched by the regex.
2205 * @param array $rawattr The original unmodified attributes.
2207 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 );
2211 * Audio embed handler callback.
2215 * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
2216 * @param array $attr Embed attributes.
2217 * @param string $url The original URL that was matched by the regex.
2218 * @param array $rawattr The original unmodified attributes.
2219 * @return string The embed HTML.
2221 function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
2222 $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
2225 * Filter the audio embed output.
2229 * @param string $audio Audio embed output.
2230 * @param array $attr An array of embed attributes.
2231 * @param string $url The original URL that was matched by the regex.
2232 * @param array $rawattr The original unmodified attributes.
2234 return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
2238 * Video embed handler callback.
2242 * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
2243 * @param array $attr Embed attributes.
2244 * @param string $url The original URL that was matched by the regex.
2245 * @param array $rawattr The original unmodified attributes.
2246 * @return string The embed HTML.
2248 function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
2250 if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
2251 $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
2252 $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
2254 $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
2257 * Filter the video embed output.
2261 * @param string $video Video embed output.
2262 * @param array $attr An array of embed attributes.
2263 * @param string $url The original URL that was matched by the regex.
2264 * @param array $rawattr The original unmodified attributes.
2266 return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
2270 * Converts a shorthand byte value to an integer byte value.
2274 * @param string $size A shorthand byte value.
2275 * @return int An integer byte value.
2277 function wp_convert_hr_to_bytes( $size ) {
2278 $size = strtolower( $size );
2279 $bytes = (int) $size;
2280 if ( strpos( $size, 'k' ) !== false )
2281 $bytes = intval( $size ) * 1024;
2282 elseif ( strpos( $size, 'm' ) !== false )
2283 $bytes = intval($size) * 1024 * 1024;
2284 elseif ( strpos( $size, 'g' ) !== false )
2285 $bytes = intval( $size ) * 1024 * 1024 * 1024;
2290 * Determine the maximum upload size allowed in php.ini.
2294 * @return int Allowed upload size.
2296 function wp_max_upload_size() {
2297 $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2298 $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2301 * Filter the maximum upload size allowed in php.ini.
2305 * @param int $size Max upload size limit in bytes.
2306 * @param int $u_bytes Maximum upload filesize in bytes.
2307 * @param int $p_bytes Maximum size of POST data in bytes.
2309 return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2313 * Returns a WP_Image_Editor instance and loads file into it.
2318 * @param string $path Path to file to load
2319 * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
2320 * @return WP_Image_Editor|WP_Error
2322 function wp_get_image_editor( $path, $args = array() ) {
2323 $args['path'] = $path;
2325 if ( ! isset( $args['mime_type'] ) ) {
2326 $file_info = wp_check_filetype( $args['path'] );
2328 // If $file_info['type'] is false, then we let the editor attempt to
2329 // figure out the file type, rather than forcing a failure based on extension.
2330 if ( isset( $file_info ) && $file_info['type'] )
2331 $args['mime_type'] = $file_info['type'];
2334 $implementation = _wp_image_editor_choose( $args );
2336 if ( $implementation ) {
2337 $editor = new $implementation( $path );
2338 $loaded = $editor->load();
2340 if ( is_wp_error( $loaded ) )
2346 return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
2350 * Tests whether there is an editor that supports a given mime type or methods.
2355 * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
2356 * @return boolean true if an eligible editor is found; false otherwise
2358 function wp_image_editor_supports( $args = array() ) {
2359 return (bool) _wp_image_editor_choose( $args );
2363 * Tests which editors are capable of supporting the request.
2368 * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
2369 * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
2371 function _wp_image_editor_choose( $args = array() ) {
2372 require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
2373 require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
2374 require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
2377 * Filter the list of image editing library classes.
2381 * @param array $image_editors List of available image editors. Defaults are
2382 * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
2384 $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
2386 foreach ( $implementations as $implementation ) {
2387 if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
2390 if ( isset( $args['mime_type'] ) &&
2392 array( $implementation, 'supports_mime_type' ),
2393 $args['mime_type'] ) ) {
2397 if ( isset( $args['methods'] ) &&
2398 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
2402 return $implementation;
2409 * Prints default plupload arguments.
2413 function wp_plupload_default_settings() {
2416 $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
2417 if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
2420 $max_upload_size = wp_max_upload_size();
2423 'runtimes' => 'html5,flash,silverlight,html4',
2424 'file_data_name' => 'async-upload', // key passed to $_FILE.
2425 'url' => admin_url( 'async-upload.php', 'relative' ),
2426 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
2427 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
2429 'max_file_size' => $max_upload_size . 'b',
2433 // Multi-file uploading doesn't currently work in iOS Safari,
2434 // single-file allows the built-in camera to be used as source for images
2435 if ( wp_is_mobile() )
2436 $defaults['multi_selection'] = false;
2439 * Filter the Plupload default settings.
2443 * @param array $defaults Default Plupload settings array.
2445 $defaults = apply_filters( 'plupload_default_settings', $defaults );
2448 'action' => 'upload-attachment',
2452 * Filter the Plupload default parameters.
2456 * @param array $params Default Plupload parameters array.
2458 $params = apply_filters( 'plupload_default_params', $params );
2459 $params['_wpnonce'] = wp_create_nonce( 'media-form' );
2460 $defaults['multipart_params'] = $params;
2463 'defaults' => $defaults,
2465 'mobile' => wp_is_mobile(),
2466 'supported' => _device_can_upload(),
2468 'limitExceeded' => is_multisite() && ! is_upload_space_available()
2471 $script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
2474 $script = "$data\n$script";
2476 $wp_scripts->add_data( 'wp-plupload', 'data', $script );
2478 add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
2481 * Prepares an attachment post object for JS, where it is expected
2482 * to be JSON-encoded and fit into an Attachment model.
2486 * @param mixed $attachment Attachment ID or object.
2487 * @return array Array of attachment details.
2489 function wp_prepare_attachment_for_js( $attachment ) {
2490 if ( ! $attachment = get_post( $attachment ) )
2493 if ( 'attachment' != $attachment->post_type )
2496 $meta = wp_get_attachment_metadata( $attachment->ID );
2497 if ( false !== strpos( $attachment->post_mime_type, '/' ) )
2498 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
2500 list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
2502 $attachment_url = wp_get_attachment_url( $attachment->ID );
2505 'id' => $attachment->ID,
2506 'title' => $attachment->post_title,
2507 'filename' => wp_basename( $attachment->guid ),
2508 'url' => $attachment_url,
2509 'link' => get_attachment_link( $attachment->ID ),
2510 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
2511 'author' => $attachment->post_author,
2512 'description' => $attachment->post_content,
2513 'caption' => $attachment->post_excerpt,
2514 'name' => $attachment->post_name,
2515 'status' => $attachment->post_status,
2516 'uploadedTo' => $attachment->post_parent,
2517 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
2518 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
2519 'menuOrder' => $attachment->menu_order,
2520 'mime' => $attachment->post_mime_type,
2522 'subtype' => $subtype,
2523 'icon' => wp_mime_type_icon( $attachment->ID ),
2524 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
2530 'editLink' => false,
2533 if ( current_user_can( 'edit_post', $attachment->ID ) ) {
2534 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
2535 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
2536 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
2539 if ( current_user_can( 'delete_post', $attachment->ID ) )
2540 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
2542 if ( $meta && 'image' === $type ) {
2545 /** This filter is documented in wp-admin/includes/media.php */
2546 $possible_sizes = apply_filters( 'image_size_names_choose', array(
2547 'thumbnail' => __('Thumbnail'),
2548 'medium' => __('Medium'),
2549 'large' => __('Large'),
2550 'full' => __('Full Size'),
2552 unset( $possible_sizes['full'] );
2554 // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
2555 // First: run the image_downsize filter. If it returns something, we can use its data.
2556 // If the filter does not return something, then image_downsize() is just an expensive
2557 // way to check the image metadata, which we do second.
2558 foreach ( $possible_sizes as $size => $label ) {
2560 /** This filter is documented in wp-includes/media.php */
2561 if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
2562 if ( ! $downsize[3] )
2564 $sizes[ $size ] = array(
2565 'height' => $downsize[2],
2566 'width' => $downsize[1],
2567 'url' => $downsize[0],
2568 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
2570 } elseif ( isset( $meta['sizes'][ $size ] ) ) {
2571 if ( ! isset( $base_url ) )
2572 $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
2574 // Nothing from the filter, so consult image metadata if we have it.
2575 $size_meta = $meta['sizes'][ $size ];
2577 // We have the actual image size, but might need to further constrain it if content_width is narrower.
2578 // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
2579 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
2581 $sizes[ $size ] = array(
2582 'height' => $height,
2584 'url' => $base_url . $size_meta['file'],
2585 'orientation' => $height > $width ? 'portrait' : 'landscape',
2590 $sizes['full'] = array( 'url' => $attachment_url );
2592 if ( isset( $meta['height'], $meta['width'] ) ) {
2593 $sizes['full']['height'] = $meta['height'];
2594 $sizes['full']['width'] = $meta['width'];
2595 $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
2598 $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
2599 } elseif ( $meta && 'video' === $type ) {
2600 if ( isset( $meta['width'] ) )
2601 $response['width'] = (int) $meta['width'];
2602 if ( isset( $meta['height'] ) )
2603 $response['height'] = (int) $meta['height'];
2606 if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
2607 if ( isset( $meta['length_formatted'] ) )
2608 $response['fileLength'] = $meta['length_formatted'];
2610 $response['meta'] = array();
2611 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
2612 if ( ! empty( $meta[ $key ] ) ) {
2613 $response['meta'][ $key ] = $meta[ $key ];
2617 $id = get_post_thumbnail_id( $attachment->ID );
2618 if ( ! empty( $id ) ) {
2619 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
2620 $response['image'] = compact( 'src', 'width', 'height' );
2621 list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
2622 $response['thumb'] = compact( 'src', 'width', 'height' );
2624 $src = wp_mime_type_icon( $attachment->ID );
2627 $response['image'] = compact( 'src', 'width', 'height' );
2628 $response['thumb'] = compact( 'src', 'width', 'height' );
2632 if ( function_exists('get_compat_media_markup') )
2633 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
2636 * Filter the attachment data prepared for JavaScript.
2640 * @param array $response Array of prepared attachment data.
2641 * @param int|object $attachment Attachment ID or object.
2642 * @param array $meta Array of attachment meta data.
2644 return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
2648 * Enqueues all scripts, styles, settings, and templates necessary to use
2649 * all media JS APIs.
2653 function wp_enqueue_media( $args = array() ) {
2655 // Enqueue me just once per page, please.
2656 if ( did_action( 'wp_enqueue_media' ) )
2659 global $content_width, $wpdb;
2664 $args = wp_parse_args( $args, $defaults );
2666 // We're going to pass the old thickbox media tabs to `media_upload_tabs`
2667 // to ensure plugins will work. We will then unset those tabs.
2669 // handler action suffix => tab label
2676 /** This filter is documented in wp-admin/includes/media.php */
2677 $tabs = apply_filters( 'media_upload_tabs', $tabs );
2678 unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
2681 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
2682 'align' => get_option( 'image_default_align' ), // empty default
2683 'size' => get_option( 'image_default_size' ), // empty default
2686 $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
2687 $mimes = get_allowed_mime_types();
2688 $ext_mimes = array();
2689 foreach ( $exts as $ext ) {
2690 foreach ( $mimes as $ext_preg => $mime_match ) {
2691 if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
2692 $ext_mimes[ $ext ] = $mime_match;
2698 $has_audio = $wpdb->get_var( "
2701 WHERE post_type = 'attachment'
2702 AND post_mime_type LIKE 'audio%'
2705 $has_video = $wpdb->get_var( "
2708 WHERE post_type = 'attachment'
2709 AND post_mime_type LIKE 'video%'
2715 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
2716 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
2717 /** This filter is documented in wp-admin/includes/media.php */
2718 'captions' => ! apply_filters( 'disable_captions', '' ),
2720 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
2725 'defaultProps' => $props,
2726 'attachmentCounts' => array(
2727 'audio' => (int) $has_audio,
2728 'video' => (int) $has_video,
2730 'embedExts' => $exts,
2731 'embedMimes' => $ext_mimes,
2732 'contentWidth' => $content_width,
2736 if ( isset( $args['post'] ) ) {
2737 $post = get_post( $args['post'] );
2738 $settings['post'] = array(
2740 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
2743 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
2744 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
2745 if ( 0 === strpos( $post->post_mime_type, 'audio/' ) ) {
2746 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
2747 } elseif ( 0 === strpos( $post->post_mime_type, 'video/' ) ) {
2748 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
2752 if ( $thumbnail_support ) {
2753 $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
2754 $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
2758 $hier = $post && is_post_type_hierarchical( $post->post_type );
2762 'url' => __( 'URL' ),
2763 'addMedia' => __( 'Add Media' ),
2764 'search' => __( 'Search' ),
2765 'select' => __( 'Select' ),
2766 'cancel' => __( 'Cancel' ),
2767 'update' => __( 'Update' ),
2768 'replace' => __( 'Replace' ),
2769 'remove' => __( 'Remove' ),
2770 'back' => __( 'Back' ),
2771 /* translators: This is a would-be plural string used in the media manager.
2772 If there is not a word you can use in your language to avoid issues with the
2773 lack of plural support here, turn it into "selected: %d" then translate it.
2775 'selected' => __( '%d selected' ),
2776 'dragInfo' => __( 'Drag and drop to reorder images.' ),
2779 'uploadFilesTitle' => __( 'Upload Files' ),
2780 'uploadImagesTitle' => __( 'Upload Images' ),
2783 'mediaLibraryTitle' => __( 'Media Library' ),
2784 'insertMediaTitle' => __( 'Insert Media' ),
2785 'createNewGallery' => __( 'Create a new gallery' ),
2786 'createNewPlaylist' => __( 'Create a new playlist' ),
2787 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
2788 'returnToLibrary' => __( '← Return to library' ),
2789 'allMediaItems' => __( 'All media items' ),
2790 'noItemsFound' => __( 'No items found.' ),
2791 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
2792 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
2793 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
2796 'insertFromUrlTitle' => __( 'Insert from URL' ),
2799 'setFeaturedImageTitle' => __( 'Set Featured Image' ),
2800 'setFeaturedImage' => __( 'Set featured image' ),
2803 'createGalleryTitle' => __( 'Create Gallery' ),
2804 'editGalleryTitle' => __( 'Edit Gallery' ),
2805 'cancelGalleryTitle' => __( '← Cancel Gallery' ),
2806 'insertGallery' => __( 'Insert gallery' ),
2807 'updateGallery' => __( 'Update gallery' ),
2808 'addToGallery' => __( 'Add to gallery' ),
2809 'addToGalleryTitle' => __( 'Add to Gallery' ),
2810 'reverseOrder' => __( 'Reverse order' ),
2813 'imageDetailsTitle' => __( 'Image Details' ),
2814 'imageReplaceTitle' => __( 'Replace Image' ),
2815 'imageDetailsCancel' => __( 'Cancel Edit' ),
2816 'editImage' => __( 'Edit Image' ),
2819 'chooseImage' => __( 'Choose Image' ),
2820 'selectAndCrop' => __( 'Select and Crop' ),
2821 'skipCropping' => __( 'Skip Cropping' ),
2822 'cropImage' => __( 'Crop Image' ),
2823 'cropYourImage' => __( 'Crop your image' ),
2824 'cropping' => __( 'Cropping…' ),
2825 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
2826 'cropError' => __( 'There has been an error cropping your image.' ),
2829 'audioDetailsTitle' => __( 'Audio Details' ),
2830 'audioReplaceTitle' => __( 'Replace Audio' ),
2831 'audioAddSourceTitle' => __( 'Add Audio Source' ),
2832 'audioDetailsCancel' => __( 'Cancel Edit' ),
2835 'videoDetailsTitle' => __( 'Video Details' ),
2836 'videoReplaceTitle' => __( 'Replace Video' ),
2837 'videoAddSourceTitle' => __( 'Add Video Source' ),
2838 'videoDetailsCancel' => __( 'Cancel Edit' ),
2839 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
2840 'videoAddTrackTitle' => __( 'Add Subtitles' ),
2843 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
2844 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
2845 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
2846 'cancelPlaylistTitle' => __( '← Cancel Audio Playlist' ),
2847 'insertPlaylist' => __( 'Insert audio playlist' ),
2848 'updatePlaylist' => __( 'Update audio playlist' ),
2849 'addToPlaylist' => __( 'Add to audio playlist' ),
2850 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
2853 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
2854 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
2855 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
2856 'cancelVideoPlaylistTitle' => __( '← Cancel Video Playlist' ),
2857 'insertVideoPlaylist' => __( 'Insert video playlist' ),
2858 'updateVideoPlaylist' => __( 'Update video playlist' ),
2859 'addToVideoPlaylist' => __( 'Add to video playlist' ),
2860 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
2864 * Filter the media view settings.
2868 * @param array $settings List of media view settings.
2869 * @param WP_Post $post Post object.
2871 $settings = apply_filters( 'media_view_settings', $settings, $post );
2874 * Filter the media view strings.
2878 * @param array $strings List of media view strings.
2879 * @param WP_Post $post Post object.
2881 $strings = apply_filters( 'media_view_strings', $strings, $post );
2883 $strings['settings'] = $settings;
2885 wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
2887 wp_enqueue_script( 'media-editor' );
2888 wp_enqueue_script( 'media-audiovideo' );
2889 wp_enqueue_style( 'media-views' );
2891 wp_enqueue_script( 'mce-view' );
2892 wp_enqueue_script( 'image-edit' );
2894 wp_enqueue_style( 'imgareaselect' );
2895 wp_plupload_default_settings();
2897 require_once ABSPATH . WPINC . '/media-template.php';
2898 add_action( 'admin_footer', 'wp_print_media_templates' );
2899 add_action( 'wp_footer', 'wp_print_media_templates' );
2900 add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
2903 * Fires at the conclusion of wp_enqueue_media().
2907 do_action( 'wp_enqueue_media' );
2911 * Retrieve media attached to the passed post.
2915 * @param string $type (Mime) type of media desired
2916 * @param mixed $post Post ID or object
2917 * @return array Found attachments
2919 function get_attached_media( $type, $post = 0 ) {
2920 if ( ! $post = get_post( $post ) )
2924 'post_parent' => $post->ID,
2925 'post_type' => 'attachment',
2926 'post_mime_type' => $type,
2927 'posts_per_page' => -1,
2928 'orderby' => 'menu_order',
2933 * Filter arguments used to retrieve media attached to the given post.
2937 * @param array $args Post query arguments.
2938 * @param string $type Mime type of the desired media.
2939 * @param mixed $post Post ID or object.
2941 $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
2943 $children = get_children( $args );
2950 * @param array $children Associative array of media attached to the given post.
2951 * @param string $type Mime type of the media desired.
2952 * @param mixed $post Post ID or object.
2954 return (array) apply_filters( 'get_attached_media', $children, $type, $post );
2958 * Check the content blob for an <audio>, <video> <object>, <embed>, or <iframe>
2962 * @param string $content A string which might contain media data.
2963 * @param array $types array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'
2964 * @return array A list of found HTML media embeds
2966 function get_media_embedded_in_content( $content, $types = null ) {
2968 $allowed_media_types = array( 'audio', 'video', 'object', 'embed', 'iframe' );
2969 if ( ! empty( $types ) ) {
2970 if ( ! is_array( $types ) )
2971 $types = array( $types );
2972 $allowed_media_types = array_intersect( $allowed_media_types, $types );
2975 foreach ( $allowed_media_types as $tag ) {
2976 if ( preg_match( '#' . get_tag_regex( $tag ) . '#', $content, $matches ) ) {
2977 $html[] = $matches[0];
2985 * Retrieve galleries from the passed post's content.
2989 * @param int|WP_Post $post Optional. Post ID or object.
2990 * @param bool $html Whether to return HTML or data in the array.
2991 * @return array A list of arrays, each containing gallery data and srcs parsed
2992 * from the expanded shortcode.
2994 function get_post_galleries( $post, $html = true ) {
2995 if ( ! $post = get_post( $post ) )
2998 if ( ! has_shortcode( $post->post_content, 'gallery' ) )
3001 $galleries = array();
3002 if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
3003 foreach ( $matches as $shortcode ) {
3004 if ( 'gallery' === $shortcode[2] ) {
3008 $gallery = do_shortcode_tag( $shortcode );
3010 $galleries[] = $gallery;
3012 preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
3013 if ( ! empty( $src ) ) {
3014 foreach ( $src as $s )
3018 $data = shortcode_parse_atts( $shortcode[3] );
3019 $data['src'] = array_values( array_unique( $srcs ) );
3020 $galleries[] = $data;
3027 * Filter the list of all found galleries in the given post.
3031 * @param array $galleries Associative array of all found post galleries.
3032 * @param WP_Post $post Post object.
3034 return apply_filters( 'get_post_galleries', $galleries, $post );
3038 * Check a specified post's content for gallery and, if present, return the first
3042 * @param int|WP_Post $post Optional. Post ID or object.
3043 * @param bool $html Whether to return HTML or data.
3044 * @return string|array Gallery data and srcs parsed from the expanded shortcode.
3046 function get_post_gallery( $post = 0, $html = true ) {
3047 $galleries = get_post_galleries( $post, $html );
3048 $gallery = reset( $galleries );
3051 * Filter the first-found post gallery.
3055 * @param array $gallery The first-found post gallery.
3056 * @param int|WP_Post $post Post ID or object.
3057 * @param array $galleries Associative array of all found post galleries.
3059 return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
3063 * Retrieve the image srcs from galleries from a post's content, if present
3067 * @param mixed $post Optional. Post ID or object.
3068 * @return array A list of lists, each containing image srcs parsed
3069 * from an expanded shortcode
3071 function get_post_galleries_images( $post = 0 ) {
3072 $galleries = get_post_galleries( $post, false );
3073 return wp_list_pluck( $galleries, 'src' );
3077 * Check a post's content for galleries and return the image srcs for the first found gallery
3081 * @param mixed $post Optional. Post ID or object.
3082 * @return array A list of a gallery's image srcs in order
3084 function get_post_gallery_images( $post = 0 ) {
3085 $gallery = get_post_gallery( $post, false );
3086 return empty( $gallery['src'] ) ? array() : $gallery['src'];
3090 * Maybe attempt to generate attachment metadata, if missing.
3094 * @param WP_Post $attachment Attachment object.
3096 function wp_maybe_generate_attachment_metadata( $attachment ) {
3097 if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
3101 $file = get_attached_file( $attachment_id );
3102 $meta = wp_get_attachment_metadata( $attachment_id );
3103 if ( empty( $meta ) && file_exists( $file ) ) {
3104 $_meta = get_post_meta( $attachment_id );
3105 $regeneration_lock = 'wp_generating_att_' . $attachment_id;
3106 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
3107 set_transient( $regeneration_lock, $file );
3108 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
3109 delete_transient( $regeneration_lock );