3 * WordPress API for media display.
9 * Scale down the default size of an image.
11 * This is so that the image is a better fit for the editor and theme.
13 * The $size parameter accepts either an array or a string. The supported string
14 * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
15 * 128 width and 96 height in pixels. Also supported for the string value is
16 * 'medium' and 'full'. The 'full' isn't actually supported, but any value other
17 * than the supported will result in the content_width size or 500 if that is
20 * Finally, there is a filter named, 'editor_max_image_size' that will be called
21 * on the calculated array for width and height, respectively. The second
22 * parameter will be the value that was in the $size parameter. The returned
23 * type for the hook is an array with the width as the first element and the
24 * height as the second element.
27 * @uses wp_constrain_dimensions() This function passes the widths and the heights.
29 * @param int $width Width of the image
30 * @param int $height Height of the image
31 * @param string|array $size Size of what the result image should be.
32 * @return array Width and height of what the result image should resize to.
34 function image_constrain_size_for_editor($width, $height, $size = 'medium') {
35 global $content_width, $_wp_additional_image_sizes;
37 if ( is_array($size) ) {
38 $max_width = $size[0];
39 $max_height = $size[1];
41 elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
42 $max_width = intval(get_option('thumbnail_size_w'));
43 $max_height = intval(get_option('thumbnail_size_h'));
44 // last chance thumbnail size defaults
45 if ( !$max_width && !$max_height ) {
50 elseif ( $size == 'medium' ) {
51 $max_width = intval(get_option('medium_size_w'));
52 $max_height = intval(get_option('medium_size_h'));
53 // if no width is set, default to the theme content width if available
55 elseif ( $size == 'large' ) {
56 // we're inserting a large size image into the editor. if it's a really
57 // big image we'll scale it down to fit reasonably within the editor
58 // itself, and within the theme's content width if it's known. the user
59 // can resize it in the editor if they wish.
60 $max_width = intval(get_option('large_size_w'));
61 $max_height = intval(get_option('large_size_h'));
62 if ( intval($content_width) > 0 )
63 $max_width = min( intval($content_width), $max_width );
64 } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
65 $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
66 $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
67 if ( intval($content_width) > 0 && is_admin() ) // Only in admin. Assume that theme authors know what they're doing.
68 $max_width = min( intval($content_width), $max_width );
70 // $size == 'full' has no constraint
73 $max_height = $height;
76 list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size );
78 return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
82 * Retrieve width and height attributes using given width and height values.
84 * Both attributes are required in the sense that both parameters must have a
85 * value, but are optional in that if you set them to false or null, then they
86 * will not be added to the returned string.
88 * You can set the value using a string, but it will only take numeric values.
89 * If you wish to put 'px' after the numbers, then it will be stripped out of
94 * @param int|string $width Optional. Width attribute value.
95 * @param int|string $height Optional. Height attribute value.
96 * @return string HTML attributes for width and, or height.
98 function image_hwstring($width, $height) {
101 $out .= 'width="'.intval($width).'" ';
103 $out .= 'height="'.intval($height).'" ';
108 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
110 * Array with image url, width, height, and whether is intermediate size, in
111 * that order is returned on success is returned. $is_intermediate is true if
112 * $url is a resized image, false if it is the original.
114 * The URL might be the original image, or it might be a resized version. This
115 * function won't create a new resized copy, it will just return an already
116 * resized one if it exists.
118 * A plugin may use the 'image_downsize' filter to hook into and offer image
119 * resizing services for images. The hook must return an array with the same
120 * elements that are returned in the function. The first element being the URL
121 * to the new image that was resized.
124 * @uses apply_filters() Calls 'image_downsize' on $id and $size to provide
127 * @param int $id Attachment ID for image.
128 * @param string $size Optional, default is 'medium'. Size of image, can be 'thumbnail'.
129 * @return bool|array False on failure, array on success.
131 function image_downsize($id, $size = 'medium') {
133 if ( !wp_attachment_is_image($id) )
136 $img_url = wp_get_attachment_url($id);
137 $meta = wp_get_attachment_metadata($id);
138 $width = $height = 0;
139 $is_intermediate = false;
140 $img_url_basename = wp_basename($img_url);
142 // plugins can use this to provide resize services
143 if ( $out = apply_filters('image_downsize', false, $id, $size) )
146 // try for a new style intermediate size
147 if ( $intermediate = image_get_intermediate_size($id, $size) ) {
148 $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
149 $width = $intermediate['width'];
150 $height = $intermediate['height'];
151 $is_intermediate = true;
153 elseif ( $size == 'thumbnail' ) {
154 // fall back to the old thumbnail
155 if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
156 $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
159 $is_intermediate = true;
162 if ( !$width && !$height && isset($meta['width'], $meta['height']) ) {
163 // any other type: use the real image
164 $width = $meta['width'];
165 $height = $meta['height'];
169 // we have the actual image size, but might need to further constrain it if content_width is narrower
170 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
172 return array( $img_url, $width, $height, $is_intermediate );
179 * Registers a new image size
181 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
182 global $_wp_additional_image_sizes;
183 $_wp_additional_image_sizes[$name] = array( 'width' => absint( $width ), 'height' => absint( $height ), 'crop' => (bool) $crop );
187 * Registers an image size for the post thumbnail
189 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
190 add_image_size( 'post-thumbnail', $width, $height, $crop );
194 * An <img src /> tag for an image attachment, scaling it down if requested.
196 * The filter 'get_image_tag_class' allows for changing the class name for the
197 * image without having to use regular expressions on the HTML content. The
198 * parameters are: what WordPress will use for the class, the Attachment ID,
199 * image align value, and the size the image should be.
201 * The second filter 'get_image_tag' has the HTML content, which can then be
202 * further manipulated by a plugin to change all attribute values and even HTML
207 * @uses apply_filters() The 'get_image_tag_class' filter is the IMG element
209 * @uses apply_filters() The 'get_image_tag' filter is the full IMG element with
212 * @param int $id Attachment ID.
213 * @param string $alt Image Description for the alt attribute.
214 * @param string $title Image Description for the title attribute.
215 * @param string $align Part of the class name for aligning the image.
216 * @param string $size Optional. Default is 'medium'.
217 * @return string HTML IMG element for given image attachment
219 function get_image_tag($id, $alt, $title, $align, $size='medium') {
221 list( $img_src, $width, $height ) = image_downsize($id, $size);
222 $hwstring = image_hwstring($width, $height);
224 $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
225 $class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
227 $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title="' . esc_attr($title).'" '.$hwstring.'class="'.$class.'" />';
229 $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
235 * Load an image from a string, if PHP supports it.
239 * @param string $file Filename of the image to load.
240 * @return resource The resulting image resource on success, Error string on failure.
242 function wp_load_image( $file ) {
243 if ( is_numeric( $file ) )
244 $file = get_attached_file( $file );
246 if ( ! file_exists( $file ) )
247 return sprintf(__('File “%s” doesn’t exist?'), $file);
249 if ( ! function_exists('imagecreatefromstring') )
250 return __('The GD image library is not installed.');
252 // Set artificially high because GD uses uncompressed images in memory
253 @ini_set('memory_limit', '256M');
254 $image = imagecreatefromstring( file_get_contents( $file ) );
256 if ( !is_resource( $image ) )
257 return sprintf(__('File “%s” is not an image.'), $file);
263 * Calculates the new dimentions for a downsampled image.
265 * If either width or height are empty, no constraint is applied on
270 * @param int $current_width Current width of the image.
271 * @param int $current_height Current height of the image.
272 * @param int $max_width Optional. Maximum wanted width.
273 * @param int $max_height Optional. Maximum wanted height.
274 * @return array First item is the width, the second item is the height.
276 function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
277 if ( !$max_width and !$max_height )
278 return array( $current_width, $current_height );
280 $width_ratio = $height_ratio = 1.0;
281 $did_width = $did_height = false;
283 if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
284 $width_ratio = $max_width / $current_width;
288 if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
289 $height_ratio = $max_height / $current_height;
293 // Calculate the larger/smaller ratios
294 $smaller_ratio = min( $width_ratio, $height_ratio );
295 $larger_ratio = max( $width_ratio, $height_ratio );
297 if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
298 // The larger ratio is too big. It would result in an overflow.
299 $ratio = $smaller_ratio;
301 // The larger ratio fits, and is likely to be a more "snug" fit.
302 $ratio = $larger_ratio;
304 $w = intval( $current_width * $ratio );
305 $h = intval( $current_height * $ratio );
307 // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
308 // We also have issues with recursive calls resulting in an ever-changing result. Contraining to the result of a constraint should yield the original result.
309 // Thus we look for dimensions that are one pixel shy of the max value and bump them up
310 if ( $did_width && $w == $max_width - 1 )
311 $w = $max_width; // Round it up
312 if ( $did_height && $h == $max_height - 1 )
313 $h = $max_height; // Round it up
315 return array( $w, $h );
319 * Retrieve calculated resized dimensions for use in imagecopyresampled().
321 * Calculate dimensions and coordinates for a resized image that fits within a
322 * specified width and height. If $crop is true, the largest matching central
323 * portion of the image will be cropped out and resized to the required size.
327 * @param int $orig_w Original width.
328 * @param int $orig_h Original height.
329 * @param int $dest_w New width.
330 * @param int $dest_h New height.
331 * @param bool $crop Optional, default is false. Whether to crop image or resize.
332 * @return bool|array False, on failure. Returned array matches parameters for imagecopyresampled() PHP function.
334 function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
336 if ($orig_w <= 0 || $orig_h <= 0)
338 // at least one of dest_w or dest_h must be specific
339 if ($dest_w <= 0 && $dest_h <= 0)
343 // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
344 $aspect_ratio = $orig_w / $orig_h;
345 $new_w = min($dest_w, $orig_w);
346 $new_h = min($dest_h, $orig_h);
349 $new_w = intval($new_h * $aspect_ratio);
353 $new_h = intval($new_w / $aspect_ratio);
356 $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
358 $crop_w = round($new_w / $size_ratio);
359 $crop_h = round($new_h / $size_ratio);
361 $s_x = floor( ($orig_w - $crop_w) / 2 );
362 $s_y = floor( ($orig_h - $crop_h) / 2 );
364 // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
371 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
374 // if the resulting image would be the same size or larger we don't want to resize it
375 if ( $new_w >= $orig_w && $new_h >= $orig_h )
378 // the return array matches the parameters to imagecopyresampled()
379 // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
380 return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
385 * Scale down an image to fit a particular size and save a new copy of the image.
387 * The PNG transparency will be preserved using the function, as well as the
388 * image type. If the file going in is PNG, then the resized image is going to
389 * be PNG. The only supported image types are PNG, GIF, and JPEG.
391 * Some functionality requires API to exist, so some PHP version may lose out
392 * support. This is not the fault of WordPress (where functionality is
393 * downgraded, not actual defects), but of your PHP version.
397 * @param string $file Image file path.
398 * @param int $max_w Maximum width to resize to.
399 * @param int $max_h Maximum height to resize to.
400 * @param bool $crop Optional. Whether to crop image or resize.
401 * @param string $suffix Optional. File Suffix.
402 * @param string $dest_path Optional. New image file path.
403 * @param int $jpeg_quality Optional, default is 90. Image quality percentage.
404 * @return mixed WP_Error on failure. String with new destination path.
406 function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
408 $image = wp_load_image( $file );
409 if ( !is_resource( $image ) )
410 return new WP_Error( 'error_loading_image', $image, $file );
412 $size = @getimagesize( $file );
414 return new WP_Error('invalid_image', __('Could not read image size'), $file);
415 list($orig_w, $orig_h, $orig_type) = $size;
417 $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
419 return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
420 list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
422 $newimage = wp_imagecreatetruecolor( $dst_w, $dst_h );
424 imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
426 // convert from full colors to index colors, like original PNG.
427 if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )
428 imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );
430 // we don't need the original in memory anymore
431 imagedestroy( $image );
433 // $suffix will be appended to the destination filename, just before the extension
435 $suffix = "{$dst_w}x{$dst_h}";
437 $info = pathinfo($file);
438 $dir = $info['dirname'];
439 $ext = $info['extension'];
440 $name = wp_basename($file, ".$ext");
442 if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
444 $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
446 if ( IMAGETYPE_GIF == $orig_type ) {
447 if ( !imagegif( $newimage, $destfilename ) )
448 return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
449 } elseif ( IMAGETYPE_PNG == $orig_type ) {
450 if ( !imagepng( $newimage, $destfilename ) )
451 return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
453 // all other formats are converted to jpg
454 $destfilename = "{$dir}/{$name}-{$suffix}.jpg";
455 if ( !imagejpeg( $newimage, $destfilename, apply_filters( 'jpeg_quality', $jpeg_quality, 'image_resize' ) ) )
456 return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
459 imagedestroy( $newimage );
461 // Set correct file permissions
462 $stat = stat( dirname( $destfilename ));
463 $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
464 @ chmod( $destfilename, $perms );
466 return $destfilename;
470 * Resize an image to make a thumbnail or intermediate size.
472 * The returned array has the file size, the image width, and image height. The
473 * filter 'image_make_intermediate_size' can be used to hook in and change the
474 * values of the returned array. The only parameter is the resized file path.
478 * @param string $file File path.
479 * @param int $width Image width.
480 * @param int $height Image height.
481 * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
482 * @return bool|array False, if no image was created. Metadata array on success.
484 function image_make_intermediate_size($file, $width, $height, $crop=false) {
485 if ( $width || $height ) {
486 $resized_file = image_resize($file, $width, $height, $crop);
487 if ( !is_wp_error($resized_file) && $resized_file && $info = getimagesize($resized_file) ) {
488 $resized_file = apply_filters('image_make_intermediate_size', $resized_file);
490 'file' => wp_basename( $resized_file ),
492 'height' => $info[1],
500 * Retrieve the image's intermediate size (resized) path, width, and height.
502 * The $size parameter can be an array with the width and height respectively.
503 * If the size matches the 'sizes' metadata array for width and height, then it
504 * will be used. If there is no direct match, then the nearest image size larger
505 * than the specified size will be used. If nothing is found, then the function
506 * will break out and return false.
508 * The metadata 'sizes' is used for compatible sizes that can be used for the
509 * parameter $size value.
511 * The url path will be given, when the $size parameter is a string.
513 * If you are passing an array for the $size, you should consider using
514 * add_image_size() so that a cropped version is generated. It's much more
515 * efficient than having to find the closest-sized image and then having the
516 * browser scale down the image.
519 * @see add_image_size()
521 * @param int $post_id Attachment ID for image.
522 * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
523 * @return bool|array False on failure or array of file path, width, and height on success.
525 function image_get_intermediate_size($post_id, $size='thumbnail') {
526 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
529 // get the best one for a specified set of dimensions
530 if ( is_array($size) && !empty($imagedata['sizes']) ) {
531 foreach ( $imagedata['sizes'] as $_size => $data ) {
532 // already cropped to width or height; so use this size
533 if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
534 $file = $data['file'];
535 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
536 return compact( 'file', 'width', 'height' );
538 // add to lookup table: area => size
539 $areas[$data['width'] * $data['height']] = $_size;
541 if ( !$size || !empty($areas) ) {
542 // find for the smallest image not smaller than the desired size
544 foreach ( $areas as $_size ) {
545 $data = $imagedata['sizes'][$_size];
546 if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
547 // Skip images with unexpectedly divergent aspect ratios (crops)
548 // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
549 $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
550 // 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
551 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'] ) ) )
553 // If we're still here, then we're going to use this size
554 $file = $data['file'];
555 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
556 return compact( 'file', 'width', 'height' );
562 if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
565 $data = $imagedata['sizes'][$size];
566 // include the full filesystem path of the intermediate file
567 if ( empty($data['path']) && !empty($data['file']) ) {
568 $file_url = wp_get_attachment_url($post_id);
569 $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
570 $data['url'] = path_join( dirname($file_url), $data['file'] );
576 * Get the available image sizes
578 * @return array Returns a filtered array of image size strings
580 function get_intermediate_image_sizes() {
581 global $_wp_additional_image_sizes;
582 $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
583 if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
584 $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
586 return apply_filters( 'intermediate_image_sizes', $image_sizes );
590 * Retrieve an image to represent an attachment.
592 * A mime icon for files, thumbnail or intermediate size for images.
596 * @param int $attachment_id Image attachment ID.
597 * @param string $size Optional, default is 'thumbnail'.
598 * @param bool $icon Optional, default is false. Whether it is an icon.
599 * @return bool|array Returns an array (url, width, height), or false, if no image is available.
601 function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
603 // get a thumbnail or intermediate image if there is one
604 if ( $image = image_downsize($attachment_id, $size) )
609 if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
610 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
611 $src_file = $icon_dir . '/' . wp_basename($src);
612 @list($width, $height) = getimagesize($src_file);
614 if ( $src && $width && $height )
615 return array( $src, $width, $height );
620 * Get an HTML img element representing an image attachment
622 * While $size will accept an array, it is better to register a size with
623 * add_image_size() so that a cropped version is generated. It's much more
624 * efficient than having to find the closest-sized image and then having the
625 * browser scale down the image.
627 * @see add_image_size()
628 * @uses apply_filters() Calls 'wp_get_attachment_image_attributes' hook on attributes array
629 * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
632 * @param int $attachment_id Image attachment ID.
633 * @param string $size Optional, default is 'thumbnail'.
634 * @param bool $icon Optional, default is false. Whether it is an icon.
635 * @return string HTML img element or empty string on failure.
637 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
640 $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
642 list($src, $width, $height) = $image;
643 $hwstring = image_hwstring($width, $height);
644 if ( is_array($size) )
645 $size = join('x', $size);
646 $attachment =& get_post($attachment_id);
647 $default_attr = array(
649 'class' => "attachment-$size",
650 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
651 'title' => trim(strip_tags( $attachment->post_title )),
653 if ( empty($default_attr['alt']) )
654 $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
655 if ( empty($default_attr['alt']) )
656 $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
658 $attr = wp_parse_args($attr, $default_attr);
659 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
660 $attr = array_map( 'esc_attr', $attr );
661 $html = rtrim("<img $hwstring");
662 foreach ( $attr as $name => $value ) {
663 $html .= " $name=" . '"' . $value . '"';
672 * Adds a 'wp-post-image' class to post thumbnail thumbnails
673 * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
674 * dynamically add/remove itself so as to only filter post thumbnail thumbnails
677 * @param array $attr Attributes including src, class, alt, title
680 function _wp_post_thumbnail_class_filter( $attr ) {
681 $attr['class'] .= ' wp-post-image';
686 * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
690 function _wp_post_thumbnail_class_filter_add( $attr ) {
691 add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
695 * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
699 function _wp_post_thumbnail_class_filter_remove( $attr ) {
700 remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
703 add_shortcode('wp_caption', 'img_caption_shortcode');
704 add_shortcode('caption', 'img_caption_shortcode');
707 * The Caption shortcode.
709 * Allows a plugin to replace the content that would otherwise be returned. The
710 * filter is 'img_caption_shortcode' and passes an empty string, the attr
711 * parameter and the content parameter values.
713 * The supported attributes for the shortcode are 'id', 'align', 'width', and
718 * @param array $attr Attributes attributed to the shortcode.
719 * @param string $content Optional. Shortcode content.
722 function img_caption_shortcode($attr, $content = null) {
724 // Allow plugins/themes to override the default caption template.
725 $output = apply_filters('img_caption_shortcode', '', $attr, $content);
729 extract(shortcode_atts(array(
731 'align' => 'alignnone',
736 if ( 1 > (int) $width || empty($caption) )
739 if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
741 return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
742 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
745 add_shortcode('gallery', 'gallery_shortcode');
748 * The Gallery shortcode.
750 * This implements the functionality of the Gallery Shortcode for displaying
751 * WordPress images on a post.
755 * @param array $attr Attributes attributed to the shortcode.
756 * @return string HTML content to display gallery.
758 function gallery_shortcode($attr) {
759 global $post, $wp_locale;
761 static $instance = 0;
764 // Allow plugins/themes to override the default gallery template.
765 $output = apply_filters('post_gallery', '', $attr);
769 // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
770 if ( isset( $attr['orderby'] ) ) {
771 $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
772 if ( !$attr['orderby'] )
773 unset( $attr['orderby'] );
776 extract(shortcode_atts(array(
778 'orderby' => 'menu_order ID',
782 'captiontag' => 'dd',
784 'size' => 'thumbnail',
790 if ( 'RAND' == $order )
793 if ( !empty($include) ) {
794 $include = preg_replace( '/[^0-9,]+/', '', $include );
795 $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
797 $attachments = array();
798 foreach ( $_attachments as $key => $val ) {
799 $attachments[$val->ID] = $_attachments[$key];
801 } elseif ( !empty($exclude) ) {
802 $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
803 $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
805 $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
808 if ( empty($attachments) )
813 foreach ( $attachments as $att_id => $attachment )
814 $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
818 $itemtag = tag_escape($itemtag);
819 $captiontag = tag_escape($captiontag);
820 $columns = intval($columns);
821 $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
822 $float = is_rtl() ? 'right' : 'left';
824 $selector = "gallery-{$instance}";
826 $gallery_style = $gallery_div = '';
827 if ( apply_filters( 'use_default_gallery_style', true ) )
829 <style type='text/css'>
833 #{$selector} .gallery-item {
837 width: {$itemwidth}%;
840 border: 2px solid #cfcfcf;
842 #{$selector} .gallery-caption {
846 <!-- see gallery_shortcode() in wp-includes/media.php -->";
847 $size_class = sanitize_html_class( $size );
848 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
849 $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
852 foreach ( $attachments as $id => $attachment ) {
853 $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
855 $output .= "<{$itemtag} class='gallery-item'>";
857 <{$icontag} class='gallery-icon'>
860 if ( $captiontag && trim($attachment->post_excerpt) ) {
862 <{$captiontag} class='wp-caption-text gallery-caption'>
863 " . wptexturize($attachment->post_excerpt) . "
866 $output .= "</{$itemtag}>";
867 if ( $columns > 0 && ++$i % $columns == 0 )
868 $output .= '<br style="clear: both" />';
872 <br style='clear: both;' />
879 * Display previous image link that has the same post parent.
882 * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
883 * @param string $text Optional, default is false. If included, link will reflect $text variable.
884 * @return string HTML content.
886 function previous_image_link($size = 'thumbnail', $text = false) {
887 adjacent_image_link(true, $size, $text);
891 * Display next image link that has the same post parent.
894 * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
895 * @param string $text Optional, default is false. If included, link will reflect $text variable.
896 * @return string HTML content.
898 function next_image_link($size = 'thumbnail', $text = false) {
899 adjacent_image_link(false, $size, $text);
903 * Display next or previous image link that has the same post parent.
905 * Retrieves the current attachment object from the $post global.
909 * @param bool $prev Optional. Default is true to display previous link, true for next.
911 function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
913 $post = get_post($post);
914 $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') ));
916 foreach ( $attachments as $k => $attachment )
917 if ( $attachment->ID == $post->ID )
920 $k = $prev ? $k - 1 : $k + 1;
922 if ( isset($attachments[$k]) )
923 echo wp_get_attachment_link($attachments[$k]->ID, $size, true, false, $text);
927 * Retrieve taxonomies attached to the attachment.
931 * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
932 * @return array Empty array on failure. List of taxonomies on success.
934 function get_attachment_taxonomies($attachment) {
935 if ( is_int( $attachment ) )
936 $attachment = get_post($attachment);
937 else if ( is_array($attachment) )
938 $attachment = (object) $attachment;
940 if ( ! is_object($attachment) )
943 $filename = basename($attachment->guid);
945 $objects = array('attachment');
947 if ( false !== strpos($filename, '.') )
948 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
949 if ( !empty($attachment->post_mime_type) ) {
950 $objects[] = 'attachment:' . $attachment->post_mime_type;
951 if ( false !== strpos($attachment->post_mime_type, '/') )
952 foreach ( explode('/', $attachment->post_mime_type) as $token )
953 if ( !empty($token) )
954 $objects[] = "attachment:$token";
957 $taxonomies = array();
958 foreach ( $objects as $object )
959 if ( $taxes = get_object_taxonomies($object) )
960 $taxonomies = array_merge($taxonomies, $taxes);
962 return array_unique($taxonomies);
966 * Check if the installed version of GD supports particular image type
970 * @param string $mime_type
973 function gd_edit_image_support($mime_type) {
974 if ( function_exists('imagetypes') ) {
975 switch( $mime_type ) {
977 return (imagetypes() & IMG_JPG) != 0;
979 return (imagetypes() & IMG_PNG) != 0;
981 return (imagetypes() & IMG_GIF) != 0;
984 switch( $mime_type ) {
986 return function_exists('imagecreatefromjpeg');
988 return function_exists('imagecreatefrompng');
990 return function_exists('imagecreatefromgif');
997 * Create new GD image resource with transparency support
1001 * @param int $width Image width
1002 * @param int $height Image height
1003 * @return image resource
1005 function wp_imagecreatetruecolor($width, $height) {
1006 $img = imagecreatetruecolor($width, $height);
1007 if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
1008 imagealphablending($img, false);
1009 imagesavealpha($img, true);
1015 * API for easily embedding rich media such as videos and images into content.
1017 * @package WordPress
1022 var $handlers = array();
1024 var $usecache = true;
1025 var $linkifunknown = true;
1030 function WP_Embed() {
1031 return $this->__construct();
1037 function __construct() {
1038 // Hack to get the [embed] shortcode to run before wpautop()
1039 add_filter( 'the_content', array(&$this, 'run_shortcode'), 8 );
1041 // Shortcode placeholder for strip_shortcodes()
1042 add_shortcode( 'embed', '__return_false' );
1044 // Attempts to embed all URLs in a post
1045 if ( get_option('embed_autourls') )
1046 add_filter( 'the_content', array(&$this, 'autoembed'), 8 );
1048 // After a post is saved, invalidate the oEmbed cache
1049 add_action( 'save_post', array(&$this, 'delete_oembed_caches') );
1051 // After a post is saved, cache oEmbed items via AJAX
1052 add_action( 'edit_form_advanced', array(&$this, 'maybe_run_ajax_cache') );
1056 * Process the [embed] shortcode.
1058 * Since the [embed] shortcode needs to be run earlier than other shortcodes,
1059 * this function removes all existing shortcodes, registers the [embed] shortcode,
1060 * calls {@link do_shortcode()}, and then re-registers the old shortcodes.
1062 * @uses $shortcode_tags
1063 * @uses remove_all_shortcodes()
1064 * @uses add_shortcode()
1065 * @uses do_shortcode()
1067 * @param string $content Content to parse
1068 * @return string Content with shortcode parsed
1070 function run_shortcode( $content ) {
1071 global $shortcode_tags;
1073 // Back up current registered shortcodes and clear them all out
1074 $orig_shortcode_tags = $shortcode_tags;
1075 remove_all_shortcodes();
1077 add_shortcode( 'embed', array(&$this, 'shortcode') );
1079 // Do the shortcode (only the [embed] one is registered)
1080 $content = do_shortcode( $content );
1082 // Put the original shortcodes back
1083 $shortcode_tags = $orig_shortcode_tags;
1089 * If a post/page was saved, then output Javascript to make
1090 * an AJAX request that will call WP_Embed::cache_oembed().
1092 function maybe_run_ajax_cache() {
1095 if ( empty($post_ID) || empty($_GET['message']) || 1 != $_GET['message'] )
1099 <script type="text/javascript">
1101 jQuery(document).ready(function($){
1102 $.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post_ID ); ?>");
1110 * Register an embed handler. Do not use this function directly, use {@link wp_embed_register_handler()} instead.
1111 * This function should probably also only be used for sites that do not support oEmbed.
1113 * @param string $id An internal ID/name for the handler. Needs to be unique.
1114 * @param string $regex The regex that will be used to see if this handler should be used for a URL.
1115 * @param callback $callback The callback function that will be called if the regex is matched.
1116 * @param int $priority Optional. Used to specify the order in which the registered handlers will be tested (default: 10). Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action.
1118 function register_handler( $id, $regex, $callback, $priority = 10 ) {
1119 $this->handlers[$priority][$id] = array(
1121 'callback' => $callback,
1126 * Unregister a previously registered embed handler. Do not use this function directly, use {@link wp_embed_unregister_handler()} instead.
1128 * @param string $id The handler ID that should be removed.
1129 * @param int $priority Optional. The priority of the handler to be removed (default: 10).
1131 function unregister_handler( $id, $priority = 10 ) {
1132 if ( isset($this->handlers[$priority][$id]) )
1133 unset($this->handlers[$priority][$id]);
1137 * The {@link do_shortcode()} callback function.
1139 * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of the registered embed handlers.
1140 * If none of the regex matches and it's enabled, then the URL will be given to the {@link WP_oEmbed} class.
1142 * @uses wp_oembed_get()
1143 * @uses wp_parse_args()
1144 * @uses wp_embed_defaults()
1145 * @uses WP_Embed::maybe_make_link()
1146 * @uses get_option()
1147 * @uses current_user_can()
1148 * @uses wp_cache_get()
1149 * @uses wp_cache_set()
1150 * @uses get_post_meta()
1151 * @uses update_post_meta()
1153 * @param array $attr Shortcode attributes.
1154 * @param string $url The URL attempting to be embeded.
1155 * @return string The embed HTML on success, otherwise the original URL.
1157 function shortcode( $attr, $url = '' ) {
1164 $attr = wp_parse_args( $attr, wp_embed_defaults() );
1166 // kses converts & into & and we need to undo this
1167 // See http://core.trac.wordpress.org/ticket/11311
1168 $url = str_replace( '&', '&', $url );
1170 // Look for known internal handlers
1171 ksort( $this->handlers );
1172 foreach ( $this->handlers as $priority => $handlers ) {
1173 foreach ( $handlers as $id => $handler ) {
1174 if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
1175 if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
1176 return apply_filters( 'embed_handler_html', $return, $url, $attr );
1181 $post_ID = ( !empty($post->ID) ) ? $post->ID : null;
1182 if ( !empty($this->post_ID) ) // Potentially set by WP_Embed::cache_oembed()
1183 $post_ID = $this->post_ID;
1185 // Unknown URL format. Let oEmbed have a go.
1188 // Check for a cached result (stored in the post meta)
1189 $cachekey = '_oembed_' . md5( $url . serialize( $attr ) );
1190 if ( $this->usecache ) {
1191 $cache = get_post_meta( $post_ID, $cachekey, true );
1193 // Failures are cached
1194 if ( '{{unknown}}' === $cache )
1195 return $this->maybe_make_link( $url );
1197 if ( !empty($cache) )
1198 return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
1201 // Use oEmbed to get the HTML
1202 $attr['discover'] = ( apply_filters('embed_oembed_discover', false) && author_can( $post_ID, 'unfiltered_html' ) );
1203 $html = wp_oembed_get( $url, $attr );
1206 $cache = ( $html ) ? $html : '{{unknown}}';
1207 update_post_meta( $post_ID, $cachekey, $cache );
1209 // If there was a result, return it
1211 return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
1215 return $this->maybe_make_link( $url );
1219 * Delete all oEmbed caches.
1221 * @param int $post_ID Post ID to delete the caches for.
1223 function delete_oembed_caches( $post_ID ) {
1224 $post_metas = get_post_custom_keys( $post_ID );
1225 if ( empty($post_metas) )
1228 foreach( $post_metas as $post_meta_key ) {
1229 if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
1230 delete_post_meta( $post_ID, $post_meta_key );
1235 * Triggers a caching of all oEmbed results.
1237 * @param int $post_ID Post ID to do the caching for.
1239 function cache_oembed( $post_ID ) {
1240 $post = get_post( $post_ID );
1242 if ( empty($post->ID) || !in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', array( 'post', 'page' ) ) ) )
1245 // Trigger a caching
1246 if ( !empty($post->post_content) ) {
1247 $this->post_ID = $post->ID;
1248 $this->usecache = false;
1250 $content = $this->run_shortcode( $post->post_content );
1251 if ( get_option('embed_autourls') )
1252 $this->autoembed( $content );
1254 $this->usecache = true;
1259 * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding.
1261 * @uses WP_Embed::autoembed_callback()
1263 * @param string $content The content to be searched.
1264 * @return string Potentially modified $content.
1266 function autoembed( $content ) {
1267 return preg_replace_callback( '|^\s*(https?://[^\s"]+)\s*$|im', array(&$this, 'autoembed_callback'), $content );
1271 * Callback function for {@link WP_Embed::autoembed()}.
1273 * @uses WP_Embed::shortcode()
1275 * @param array $match A regex match array.
1276 * @return string The embed HTML on success, otherwise the original URL.
1278 function autoembed_callback( $match ) {
1279 $oldval = $this->linkifunknown;
1280 $this->linkifunknown = false;
1281 $return = $this->shortcode( array(), $match[1] );
1282 $this->linkifunknown = $oldval;
1284 return "\n$return\n";
1288 * Conditionally makes a hyperlink based on an internal class variable.
1290 * @param string $url URL to potentially be linked.
1291 * @return string Linked URL or the original URL.
1293 function maybe_make_link( $url ) {
1294 $output = ( $this->linkifunknown ) ? '<a href="' . esc_attr($url) . '">' . esc_html($url) . '</a>' : $url;
1295 return apply_filters( 'embed_maybe_make_link', $output, $url );
1298 $wp_embed = new WP_Embed();
1301 * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
1304 * @see WP_Embed::register_handler()
1306 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
1308 $wp_embed->register_handler( $id, $regex, $callback, $priority );
1312 * Unregister a previously registered embed handler.
1315 * @see WP_Embed::unregister_handler()
1317 function wp_embed_unregister_handler( $id, $priority = 10 ) {
1319 $wp_embed->unregister_handler( $id, $priority );
1323 * Create default array of embed parameters.
1327 * @return array Default embed parameters.
1329 function wp_embed_defaults() {
1330 if ( !empty($GLOBALS['content_width']) )
1331 $theme_width = (int) $GLOBALS['content_width'];
1333 $width = get_option('embed_size_w');
1335 if ( empty($width) && !empty($theme_width) )
1336 $width = $theme_width;
1338 if ( empty($width) )
1341 $height = get_option('embed_size_h');
1343 if ( empty($height) )
1346 return apply_filters( 'embed_defaults', array(
1348 'height' => $height,
1353 * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
1356 * @uses wp_constrain_dimensions() This function passes the widths and the heights.
1358 * @param int $example_width The width of an example embed.
1359 * @param int $example_height The height of an example embed.
1360 * @param int $max_width The maximum allowed width.
1361 * @param int $max_height The maximum allowed height.
1362 * @return array The maximum possible width and height based on the example ratio.
1364 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
1365 $example_width = (int) $example_width;
1366 $example_height = (int) $example_height;
1367 $max_width = (int) $max_width;
1368 $max_height = (int) $max_height;
1370 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
1374 * Attempts to fetch the embed HTML for a provided URL using oEmbed.
1379 * @uses _wp_oembed_get_object()
1380 * @uses WP_oEmbed::get_html()
1382 * @param string $url The URL that should be embeded.
1383 * @param array $args Addtional arguments and parameters.
1384 * @return string The original URL on failure or the embed HTML on success.
1386 function wp_oembed_get( $url, $args = '' ) {
1387 require_once( ABSPATH . WPINC . '/class-oembed.php' );
1388 $oembed = _wp_oembed_get_object();
1389 return $oembed->get_html( $url, $args );
1393 * Adds a URL format and oEmbed provider URL pair.
1398 * @uses _wp_oembed_get_object()
1400 * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
1401 * @param string $provider The URL to the oEmbed provider.
1402 * @param boolean $regex Whether the $format parameter is in a regex format.
1404 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
1405 require_once( ABSPATH . WPINC . '/class-oembed.php' );
1406 $oembed = _wp_oembed_get_object();
1407 $oembed->providers[$format] = array( $provider, $regex );