/wp-includes/media.php

https://bitbucket.org/skyarch-iijima/wordpress · PHP · 3958 lines · 1934 code · 440 blank · 1584 comment · 395 complexity · 1cafc46a1a5e7146d64b2ee53ab7c5c1 MD5 · raw file

Large files are truncated click here to view the full file

  1. <?php
  2. /**
  3. * WordPress API for media display.
  4. *
  5. * @package WordPress
  6. * @subpackage Media
  7. */
  8. /**
  9. * Retrieve additional image sizes.
  10. *
  11. * @since 4.7.0
  12. *
  13. * @global array $_wp_additional_image_sizes
  14. *
  15. * @return array Additional images size data.
  16. */
  17. function wp_get_additional_image_sizes() {
  18. global $_wp_additional_image_sizes;
  19. if ( ! $_wp_additional_image_sizes ) {
  20. $_wp_additional_image_sizes = array();
  21. }
  22. return $_wp_additional_image_sizes;
  23. }
  24. /**
  25. * Scale down the default size of an image.
  26. *
  27. * This is so that the image is a better fit for the editor and theme.
  28. *
  29. * The `$size` parameter accepts either an array or a string. The supported string
  30. * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
  31. * 128 width and 96 height in pixels. Also supported for the string value is
  32. * 'medium', 'medium_large' and 'full'. The 'full' isn't actually supported, but any value other
  33. * than the supported will result in the content_width size or 500 if that is
  34. * not set.
  35. *
  36. * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
  37. * called on the calculated array for width and height, respectively. The second
  38. * parameter will be the value that was in the $size parameter. The returned
  39. * type for the hook is an array with the width as the first element and the
  40. * height as the second element.
  41. *
  42. * @since 2.5.0
  43. *
  44. * @global int $content_width
  45. *
  46. * @param int $width Width of the image in pixels.
  47. * @param int $height Height of the image in pixels.
  48. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array
  49. * of width and height values in pixels (in that order).
  50. * Default 'medium'.
  51. * @param string $context Optional. Could be 'display' (like in a theme) or 'edit'
  52. * (like inserting into an editor). Default null.
  53. * @return array Width and height of what the result image should resize to.
  54. */
  55. function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
  56. global $content_width;
  57. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  58. if ( ! $context )
  59. $context = is_admin() ? 'edit' : 'display';
  60. if ( is_array($size) ) {
  61. $max_width = $size[0];
  62. $max_height = $size[1];
  63. }
  64. elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
  65. $max_width = intval(get_option('thumbnail_size_w'));
  66. $max_height = intval(get_option('thumbnail_size_h'));
  67. // last chance thumbnail size defaults
  68. if ( !$max_width && !$max_height ) {
  69. $max_width = 128;
  70. $max_height = 96;
  71. }
  72. }
  73. elseif ( $size == 'medium' ) {
  74. $max_width = intval(get_option('medium_size_w'));
  75. $max_height = intval(get_option('medium_size_h'));
  76. }
  77. elseif ( $size == 'medium_large' ) {
  78. $max_width = intval( get_option( 'medium_large_size_w' ) );
  79. $max_height = intval( get_option( 'medium_large_size_h' ) );
  80. if ( intval( $content_width ) > 0 ) {
  81. $max_width = min( intval( $content_width ), $max_width );
  82. }
  83. }
  84. elseif ( $size == 'large' ) {
  85. /*
  86. * We're inserting a large size image into the editor. If it's a really
  87. * big image we'll scale it down to fit reasonably within the editor
  88. * itself, and within the theme's content width if it's known. The user
  89. * can resize it in the editor if they wish.
  90. */
  91. $max_width = intval(get_option('large_size_w'));
  92. $max_height = intval(get_option('large_size_h'));
  93. if ( intval($content_width) > 0 ) {
  94. $max_width = min( intval($content_width), $max_width );
  95. }
  96. } elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
  97. $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
  98. $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
  99. // Only in admin. Assume that theme authors know what they're doing.
  100. if ( intval( $content_width ) > 0 && 'edit' === $context ) {
  101. $max_width = min( intval( $content_width ), $max_width );
  102. }
  103. }
  104. // $size == 'full' has no constraint
  105. else {
  106. $max_width = $width;
  107. $max_height = $height;
  108. }
  109. /**
  110. * Filters the maximum image size dimensions for the editor.
  111. *
  112. * @since 2.5.0
  113. *
  114. * @param array $max_image_size An array with the width as the first element,
  115. * and the height as the second element.
  116. * @param string|array $size Size of what the result image should be.
  117. * @param string $context The context the image is being resized for.
  118. * Possible values are 'display' (like in a theme)
  119. * or 'edit' (like inserting into an editor).
  120. */
  121. list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
  122. return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
  123. }
  124. /**
  125. * Retrieve width and height attributes using given width and height values.
  126. *
  127. * Both attributes are required in the sense that both parameters must have a
  128. * value, but are optional in that if you set them to false or null, then they
  129. * will not be added to the returned string.
  130. *
  131. * You can set the value using a string, but it will only take numeric values.
  132. * If you wish to put 'px' after the numbers, then it will be stripped out of
  133. * the return.
  134. *
  135. * @since 2.5.0
  136. *
  137. * @param int|string $width Image width in pixels.
  138. * @param int|string $height Image height in pixels.
  139. * @return string HTML attributes for width and, or height.
  140. */
  141. function image_hwstring( $width, $height ) {
  142. $out = '';
  143. if ($width)
  144. $out .= 'width="'.intval($width).'" ';
  145. if ($height)
  146. $out .= 'height="'.intval($height).'" ';
  147. return $out;
  148. }
  149. /**
  150. * Scale an image to fit a particular size (such as 'thumb' or 'medium').
  151. *
  152. * Array with image url, width, height, and whether is intermediate size, in
  153. * that order is returned on success is returned. $is_intermediate is true if
  154. * $url is a resized image, false if it is the original.
  155. *
  156. * The URL might be the original image, or it might be a resized version. This
  157. * function won't create a new resized copy, it will just return an already
  158. * resized one if it exists.
  159. *
  160. * A plugin may use the {@see 'image_downsize'} filter to hook into and offer image
  161. * resizing services for images. The hook must return an array with the same
  162. * elements that are returned in the function. The first element being the URL
  163. * to the new image that was resized.
  164. *
  165. * @since 2.5.0
  166. *
  167. * @param int $id Attachment ID for image.
  168. * @param array|string $size Optional. Image size to scale to. Accepts any valid image size,
  169. * or an array of width and height values in pixels (in that order).
  170. * Default 'medium'.
  171. * @return false|array Array containing the image URL, width, height, and boolean for whether
  172. * the image is an intermediate size. False on failure.
  173. */
  174. function image_downsize( $id, $size = 'medium' ) {
  175. $is_image = wp_attachment_is_image( $id );
  176. /**
  177. * Filters whether to preempt the output of image_downsize().
  178. *
  179. * Passing a truthy value to the filter will effectively short-circuit
  180. * down-sizing the image, returning that value as output instead.
  181. *
  182. * @since 2.5.0
  183. *
  184. * @param bool $downsize Whether to short-circuit the image downsize. Default false.
  185. * @param int $id Attachment ID for image.
  186. * @param array|string $size Size of image. Image size or array of width and height values (in that order).
  187. * Default 'medium'.
  188. */
  189. if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
  190. return $out;
  191. }
  192. $img_url = wp_get_attachment_url($id);
  193. $meta = wp_get_attachment_metadata($id);
  194. $width = $height = 0;
  195. $is_intermediate = false;
  196. $img_url_basename = wp_basename($img_url);
  197. // If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
  198. // Otherwise, a non-image type could be returned.
  199. if ( ! $is_image ) {
  200. if ( ! empty( $meta['sizes'] ) ) {
  201. $img_url = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
  202. $img_url_basename = $meta['sizes']['full']['file'];
  203. $width = $meta['sizes']['full']['width'];
  204. $height = $meta['sizes']['full']['height'];
  205. } else {
  206. return false;
  207. }
  208. }
  209. // try for a new style intermediate size
  210. if ( $intermediate = image_get_intermediate_size($id, $size) ) {
  211. $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
  212. $width = $intermediate['width'];
  213. $height = $intermediate['height'];
  214. $is_intermediate = true;
  215. }
  216. elseif ( $size == 'thumbnail' ) {
  217. // fall back to the old thumbnail
  218. if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
  219. $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
  220. $width = $info[0];
  221. $height = $info[1];
  222. $is_intermediate = true;
  223. }
  224. }
  225. if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
  226. // any other type: use the real image
  227. $width = $meta['width'];
  228. $height = $meta['height'];
  229. }
  230. if ( $img_url) {
  231. // we have the actual image size, but might need to further constrain it if content_width is narrower
  232. list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
  233. return array( $img_url, $width, $height, $is_intermediate );
  234. }
  235. return false;
  236. }
  237. /**
  238. * Register a new image size.
  239. *
  240. * Cropping behavior for the image size is dependent on the value of $crop:
  241. * 1. If false (default), images will be scaled, not cropped.
  242. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  243. * - x_crop_position accepts 'left' 'center', or 'right'.
  244. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  245. * Images will be cropped to the specified dimensions within the defined crop area.
  246. * 3. If true, images will be cropped to the specified dimensions using center positions.
  247. *
  248. * @since 2.9.0
  249. *
  250. * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
  251. *
  252. * @param string $name Image size identifier.
  253. * @param int $width Image width in pixels.
  254. * @param int $height Image height in pixels.
  255. * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
  256. * An array can specify positioning of the crop area. Default false.
  257. */
  258. function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
  259. global $_wp_additional_image_sizes;
  260. $_wp_additional_image_sizes[ $name ] = array(
  261. 'width' => absint( $width ),
  262. 'height' => absint( $height ),
  263. 'crop' => $crop,
  264. );
  265. }
  266. /**
  267. * Check if an image size exists.
  268. *
  269. * @since 3.9.0
  270. *
  271. * @param string $name The image size to check.
  272. * @return bool True if the image size exists, false if not.
  273. */
  274. function has_image_size( $name ) {
  275. $sizes = wp_get_additional_image_sizes();
  276. return isset( $sizes[ $name ] );
  277. }
  278. /**
  279. * Remove a new image size.
  280. *
  281. * @since 3.9.0
  282. *
  283. * @global array $_wp_additional_image_sizes
  284. *
  285. * @param string $name The image size to remove.
  286. * @return bool True if the image size was successfully removed, false on failure.
  287. */
  288. function remove_image_size( $name ) {
  289. global $_wp_additional_image_sizes;
  290. if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
  291. unset( $_wp_additional_image_sizes[ $name ] );
  292. return true;
  293. }
  294. return false;
  295. }
  296. /**
  297. * Registers an image size for the post thumbnail.
  298. *
  299. * @since 2.9.0
  300. *
  301. * @see add_image_size() for details on cropping behavior.
  302. *
  303. * @param int $width Image width in pixels.
  304. * @param int $height Image height in pixels.
  305. * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
  306. * An array can specify positioning of the crop area. Default false.
  307. */
  308. function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
  309. add_image_size( 'post-thumbnail', $width, $height, $crop );
  310. }
  311. /**
  312. * Gets an img tag for an image attachment, scaling it down if requested.
  313. *
  314. * The {@see 'get_image_tag_class'} filter allows for changing the class name for the
  315. * image without having to use regular expressions on the HTML content. The
  316. * parameters are: what WordPress will use for the class, the Attachment ID,
  317. * image align value, and the size the image should be.
  318. *
  319. * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be
  320. * further manipulated by a plugin to change all attribute values and even HTML
  321. * content.
  322. *
  323. * @since 2.5.0
  324. *
  325. * @param int $id Attachment ID.
  326. * @param string $alt Image Description for the alt attribute.
  327. * @param string $title Image Description for the title attribute.
  328. * @param string $align Part of the class name for aligning the image.
  329. * @param string|array $size Optional. Registered image size to retrieve a tag for. Accepts any
  330. * valid image size, or an array of width and height values in pixels
  331. * (in that order). Default 'medium'.
  332. * @return string HTML IMG element for given image attachment
  333. */
  334. function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
  335. list( $img_src, $width, $height ) = image_downsize($id, $size);
  336. $hwstring = image_hwstring($width, $height);
  337. $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
  338. $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
  339. /**
  340. * Filters the value of the attachment's image tag class attribute.
  341. *
  342. * @since 2.6.0
  343. *
  344. * @param string $class CSS class name or space-separated list of classes.
  345. * @param int $id Attachment ID.
  346. * @param string $align Part of the class name for aligning the image.
  347. * @param string|array $size Size of image. Image size or array of width and height values (in that order).
  348. * Default 'medium'.
  349. */
  350. $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
  351. $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
  352. /**
  353. * Filters the HTML content for the image tag.
  354. *
  355. * @since 2.6.0
  356. *
  357. * @param string $html HTML content for the image.
  358. * @param int $id Attachment ID.
  359. * @param string $alt Alternate text.
  360. * @param string $title Attachment title.
  361. * @param string $align Part of the class name for aligning the image.
  362. * @param string|array $size Size of image. Image size or array of width and height values (in that order).
  363. * Default 'medium'.
  364. */
  365. return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
  366. }
  367. /**
  368. * Calculates the new dimensions for a down-sampled image.
  369. *
  370. * If either width or height are empty, no constraint is applied on
  371. * that dimension.
  372. *
  373. * @since 2.5.0
  374. *
  375. * @param int $current_width Current width of the image.
  376. * @param int $current_height Current height of the image.
  377. * @param int $max_width Optional. Max width in pixels to constrain to. Default 0.
  378. * @param int $max_height Optional. Max height in pixels to constrain to. Default 0.
  379. * @return array First item is the width, the second item is the height.
  380. */
  381. function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
  382. if ( !$max_width && !$max_height )
  383. return array( $current_width, $current_height );
  384. $width_ratio = $height_ratio = 1.0;
  385. $did_width = $did_height = false;
  386. if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
  387. $width_ratio = $max_width / $current_width;
  388. $did_width = true;
  389. }
  390. if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
  391. $height_ratio = $max_height / $current_height;
  392. $did_height = true;
  393. }
  394. // Calculate the larger/smaller ratios
  395. $smaller_ratio = min( $width_ratio, $height_ratio );
  396. $larger_ratio = max( $width_ratio, $height_ratio );
  397. if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
  398. // The larger ratio is too big. It would result in an overflow.
  399. $ratio = $smaller_ratio;
  400. } else {
  401. // The larger ratio fits, and is likely to be a more "snug" fit.
  402. $ratio = $larger_ratio;
  403. }
  404. // Very small dimensions may result in 0, 1 should be the minimum.
  405. $w = max ( 1, (int) round( $current_width * $ratio ) );
  406. $h = max ( 1, (int) round( $current_height * $ratio ) );
  407. // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
  408. // 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.
  409. // Thus we look for dimensions that are one pixel shy of the max value and bump them up
  410. // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
  411. if ( $did_width && $w == $max_width - 1 ) {
  412. $w = $max_width; // Round it up
  413. }
  414. // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
  415. if ( $did_height && $h == $max_height - 1 ) {
  416. $h = $max_height; // Round it up
  417. }
  418. /**
  419. * Filters dimensions to constrain down-sampled images to.
  420. *
  421. * @since 4.1.0
  422. *
  423. * @param array $dimensions The image width and height.
  424. * @param int $current_width The current width of the image.
  425. * @param int $current_height The current height of the image.
  426. * @param int $max_width The maximum width permitted.
  427. * @param int $max_height The maximum height permitted.
  428. */
  429. return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
  430. }
  431. /**
  432. * Retrieves calculated resize dimensions for use in WP_Image_Editor.
  433. *
  434. * Calculates dimensions and coordinates for a resized image that fits
  435. * within a specified width and height.
  436. *
  437. * Cropping behavior is dependent on the value of $crop:
  438. * 1. If false (default), images will not be cropped.
  439. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  440. * - x_crop_position accepts 'left' 'center', or 'right'.
  441. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  442. * Images will be cropped to the specified dimensions within the defined crop area.
  443. * 3. If true, images will be cropped to the specified dimensions using center positions.
  444. *
  445. * @since 2.5.0
  446. *
  447. * @param int $orig_w Original width in pixels.
  448. * @param int $orig_h Original height in pixels.
  449. * @param int $dest_w New width in pixels.
  450. * @param int $dest_h New height in pixels.
  451. * @param bool|array $crop Optional. Whether to crop image to specified width and height or resize.
  452. * An array can specify positioning of the crop area. Default false.
  453. * @return false|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
  454. */
  455. function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
  456. if ($orig_w <= 0 || $orig_h <= 0)
  457. return false;
  458. // at least one of dest_w or dest_h must be specific
  459. if ($dest_w <= 0 && $dest_h <= 0)
  460. return false;
  461. /**
  462. * Filters whether to preempt calculating the image resize dimensions.
  463. *
  464. * Passing a non-null value to the filter will effectively short-circuit
  465. * image_resize_dimensions(), returning that value instead.
  466. *
  467. * @since 3.4.0
  468. *
  469. * @param null|mixed $null Whether to preempt output of the resize dimensions.
  470. * @param int $orig_w Original width in pixels.
  471. * @param int $orig_h Original height in pixels.
  472. * @param int $dest_w New width in pixels.
  473. * @param int $dest_h New height in pixels.
  474. * @param bool|array $crop Whether to crop image to specified width and height or resize.
  475. * An array can specify positioning of the crop area. Default false.
  476. */
  477. $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
  478. if ( null !== $output )
  479. return $output;
  480. if ( $crop ) {
  481. // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
  482. $aspect_ratio = $orig_w / $orig_h;
  483. $new_w = min($dest_w, $orig_w);
  484. $new_h = min($dest_h, $orig_h);
  485. if ( ! $new_w ) {
  486. $new_w = (int) round( $new_h * $aspect_ratio );
  487. }
  488. if ( ! $new_h ) {
  489. $new_h = (int) round( $new_w / $aspect_ratio );
  490. }
  491. $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
  492. $crop_w = round($new_w / $size_ratio);
  493. $crop_h = round($new_h / $size_ratio);
  494. if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
  495. $crop = array( 'center', 'center' );
  496. }
  497. list( $x, $y ) = $crop;
  498. if ( 'left' === $x ) {
  499. $s_x = 0;
  500. } elseif ( 'right' === $x ) {
  501. $s_x = $orig_w - $crop_w;
  502. } else {
  503. $s_x = floor( ( $orig_w - $crop_w ) / 2 );
  504. }
  505. if ( 'top' === $y ) {
  506. $s_y = 0;
  507. } elseif ( 'bottom' === $y ) {
  508. $s_y = $orig_h - $crop_h;
  509. } else {
  510. $s_y = floor( ( $orig_h - $crop_h ) / 2 );
  511. }
  512. } else {
  513. // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
  514. $crop_w = $orig_w;
  515. $crop_h = $orig_h;
  516. $s_x = 0;
  517. $s_y = 0;
  518. list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
  519. }
  520. // if the resulting image would be the same size or larger we don't want to resize it
  521. if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
  522. return false;
  523. }
  524. // the return array matches the parameters to imagecopyresampled()
  525. // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  526. return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
  527. }
  528. /**
  529. * Resizes an image to make a thumbnail or intermediate size.
  530. *
  531. * The returned array has the file size, the image width, and image height. The
  532. * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the
  533. * values of the returned array. The only parameter is the resized file path.
  534. *
  535. * @since 2.5.0
  536. *
  537. * @param string $file File path.
  538. * @param int $width Image width.
  539. * @param int $height Image height.
  540. * @param bool $crop Optional. Whether to crop image to specified width and height or resize.
  541. * Default false.
  542. * @return false|array False, if no image was created. Metadata array on success.
  543. */
  544. function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
  545. if ( $width || $height ) {
  546. $editor = wp_get_image_editor( $file );
  547. if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
  548. return false;
  549. $resized_file = $editor->save();
  550. if ( ! is_wp_error( $resized_file ) && $resized_file ) {
  551. unset( $resized_file['path'] );
  552. return $resized_file;
  553. }
  554. }
  555. return false;
  556. }
  557. /**
  558. * Helper function to test if aspect ratios for two images match.
  559. *
  560. * @since 4.6.0
  561. *
  562. * @param int $source_width Width of the first image in pixels.
  563. * @param int $source_height Height of the first image in pixels.
  564. * @param int $target_width Width of the second image in pixels.
  565. * @param int $target_height Height of the second image in pixels.
  566. * @return bool True if aspect ratios match within 1px. False if not.
  567. */
  568. function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
  569. /*
  570. * To test for varying crops, we constrain the dimensions of the larger image
  571. * to the dimensions of the smaller image and see if they match.
  572. */
  573. if ( $source_width > $target_width ) {
  574. $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
  575. $expected_size = array( $target_width, $target_height );
  576. } else {
  577. $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
  578. $expected_size = array( $source_width, $source_height );
  579. }
  580. // If the image dimensions are within 1px of the expected size, we consider it a match.
  581. $matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 );
  582. return $matched;
  583. }
  584. /**
  585. * Retrieves the image's intermediate size (resized) path, width, and height.
  586. *
  587. * The $size parameter can be an array with the width and height respectively.
  588. * If the size matches the 'sizes' metadata array for width and height, then it
  589. * will be used. If there is no direct match, then the nearest image size larger
  590. * than the specified size will be used. If nothing is found, then the function
  591. * will break out and return false.
  592. *
  593. * The metadata 'sizes' is used for compatible sizes that can be used for the
  594. * parameter $size value.
  595. *
  596. * The url path will be given, when the $size parameter is a string.
  597. *
  598. * If you are passing an array for the $size, you should consider using
  599. * add_image_size() so that a cropped version is generated. It's much more
  600. * efficient than having to find the closest-sized image and then having the
  601. * browser scale down the image.
  602. *
  603. * @since 2.5.0
  604. *
  605. * @param int $post_id Attachment ID.
  606. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array
  607. * of width and height values in pixels (in that order).
  608. * Default 'thumbnail'.
  609. * @return false|array $data {
  610. * Array of file relative path, width, and height on success. Additionally includes absolute
  611. * path and URL if registered size is passed to $size parameter. False on failure.
  612. *
  613. * @type string $file Image's path relative to uploads directory
  614. * @type int $width Width of image
  615. * @type int $height Height of image
  616. * @type string $path Image's absolute filesystem path.
  617. * @type string $url Image's URL.
  618. * }
  619. */
  620. function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
  621. if ( ! $size || ! is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) || empty( $imagedata['sizes'] ) ) {
  622. return false;
  623. }
  624. $data = array();
  625. // Find the best match when '$size' is an array.
  626. if ( is_array( $size ) ) {
  627. $candidates = array();
  628. if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
  629. $imagedata['height'] = $imagedata['sizes']['full']['height'];
  630. $imagedata['width'] = $imagedata['sizes']['full']['width'];
  631. }
  632. foreach ( $imagedata['sizes'] as $_size => $data ) {
  633. // If there's an exact match to an existing image size, short circuit.
  634. if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
  635. $candidates[ $data['width'] * $data['height'] ] = $data;
  636. break;
  637. }
  638. // If it's not an exact match, consider larger sizes with the same aspect ratio.
  639. if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
  640. // If '0' is passed to either size, we test ratios against the original file.
  641. if ( 0 === $size[0] || 0 === $size[1] ) {
  642. $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
  643. } else {
  644. $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
  645. }
  646. if ( $same_ratio ) {
  647. $candidates[ $data['width'] * $data['height'] ] = $data;
  648. }
  649. }
  650. }
  651. if ( ! empty( $candidates ) ) {
  652. // Sort the array by size if we have more than one candidate.
  653. if ( 1 < count( $candidates ) ) {
  654. ksort( $candidates );
  655. }
  656. $data = array_shift( $candidates );
  657. /*
  658. * When the size requested is smaller than the thumbnail dimensions, we
  659. * fall back to the thumbnail size to maintain backwards compatibility with
  660. * pre 4.6 versions of WordPress.
  661. */
  662. } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) && $imagedata['sizes']['thumbnail']['width'] >= $size[0] && $imagedata['sizes']['thumbnail']['width'] >= $size[1] ) {
  663. $data = $imagedata['sizes']['thumbnail'];
  664. } else {
  665. return false;
  666. }
  667. // Constrain the width and height attributes to the requested values.
  668. list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  669. } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
  670. $data = $imagedata['sizes'][ $size ];
  671. }
  672. // If we still don't have a match at this point, return false.
  673. if ( empty( $data ) ) {
  674. return false;
  675. }
  676. // include the full filesystem path of the intermediate file
  677. if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
  678. $file_url = wp_get_attachment_url($post_id);
  679. $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
  680. $data['url'] = path_join( dirname($file_url), $data['file'] );
  681. }
  682. /**
  683. * Filters the output of image_get_intermediate_size()
  684. *
  685. * @since 4.4.0
  686. *
  687. * @see image_get_intermediate_size()
  688. *
  689. * @param array $data Array of file relative path, width, and height on success. May also include
  690. * file absolute path and URL.
  691. * @param int $post_id The post_id of the image attachment
  692. * @param string|array $size Registered image size or flat array of initially-requested height and width
  693. * dimensions (in that order).
  694. */
  695. return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
  696. }
  697. /**
  698. * Gets the available intermediate image sizes.
  699. *
  700. * @since 3.0.0
  701. *
  702. * @return array Returns a filtered array of image size strings.
  703. */
  704. function get_intermediate_image_sizes() {
  705. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  706. $image_sizes = array('thumbnail', 'medium', 'medium_large', 'large'); // Standard sizes
  707. if ( ! empty( $_wp_additional_image_sizes ) ) {
  708. $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
  709. }
  710. /**
  711. * Filters the list of intermediate image sizes.
  712. *
  713. * @since 2.5.0
  714. *
  715. * @param array $image_sizes An array of intermediate image sizes. Defaults
  716. * are 'thumbnail', 'medium', 'medium_large', 'large'.
  717. */
  718. return apply_filters( 'intermediate_image_sizes', $image_sizes );
  719. }
  720. /**
  721. * Retrieve an image to represent an attachment.
  722. *
  723. * A mime icon for files, thumbnail or intermediate size for images.
  724. *
  725. * The returned array contains four values: the URL of the attachment image src,
  726. * the width of the image file, the height of the image file, and a boolean
  727. * representing whether the returned array describes an intermediate (generated)
  728. * image size or the original, full-sized upload.
  729. *
  730. * @since 2.5.0
  731. *
  732. * @param int $attachment_id Image attachment ID.
  733. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
  734. * and height values in pixels (in that order). Default 'thumbnail'.
  735. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  736. * @return false|array Returns an array (url, width, height, is_intermediate), or false, if no image is available.
  737. */
  738. function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
  739. // get a thumbnail or intermediate image if there is one
  740. $image = image_downsize( $attachment_id, $size );
  741. if ( ! $image ) {
  742. $src = false;
  743. if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {
  744. /** This filter is documented in wp-includes/post.php */
  745. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
  746. $src_file = $icon_dir . '/' . wp_basename( $src );
  747. @list( $width, $height ) = getimagesize( $src_file );
  748. }
  749. if ( $src && $width && $height ) {
  750. $image = array( $src, $width, $height );
  751. }
  752. }
  753. /**
  754. * Filters the image src result.
  755. *
  756. * @since 4.3.0
  757. *
  758. * @param array|false $image Either array with src, width & height, icon src, or false.
  759. * @param int $attachment_id Image attachment ID.
  760. * @param string|array $size Size of image. Image size or array of width and height values
  761. * (in that order). Default 'thumbnail'.
  762. * @param bool $icon Whether the image should be treated as an icon. Default false.
  763. */
  764. return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
  765. }
  766. /**
  767. * Get an HTML img element representing an image attachment
  768. *
  769. * While `$size` will accept an array, it is better to register a size with
  770. * add_image_size() so that a cropped version is generated. It's much more
  771. * efficient than having to find the closest-sized image and then having the
  772. * browser scale down the image.
  773. *
  774. * @since 2.5.0
  775. *
  776. * @param int $attachment_id Image attachment ID.
  777. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
  778. * and height values in pixels (in that order). Default 'thumbnail'.
  779. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  780. * @param string|array $attr Optional. Attributes for the image markup. Default empty.
  781. * @return string HTML img element or empty string on failure.
  782. */
  783. function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
  784. $html = '';
  785. $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
  786. if ( $image ) {
  787. list($src, $width, $height) = $image;
  788. $hwstring = image_hwstring($width, $height);
  789. $size_class = $size;
  790. if ( is_array( $size_class ) ) {
  791. $size_class = join( 'x', $size_class );
  792. }
  793. $attachment = get_post($attachment_id);
  794. $default_attr = array(
  795. 'src' => $src,
  796. 'class' => "attachment-$size_class size-$size_class",
  797. 'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
  798. );
  799. $attr = wp_parse_args( $attr, $default_attr );
  800. // Generate 'srcset' and 'sizes' if not already present.
  801. if ( empty( $attr['srcset'] ) ) {
  802. $image_meta = wp_get_attachment_metadata( $attachment_id );
  803. if ( is_array( $image_meta ) ) {
  804. $size_array = array( absint( $width ), absint( $height ) );
  805. $srcset = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
  806. $sizes = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
  807. if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
  808. $attr['srcset'] = $srcset;
  809. if ( empty( $attr['sizes'] ) ) {
  810. $attr['sizes'] = $sizes;
  811. }
  812. }
  813. }
  814. }
  815. /**
  816. * Filters the list of attachment image attributes.
  817. *
  818. * @since 2.8.0
  819. *
  820. * @param array $attr Attributes for the image markup.
  821. * @param WP_Post $attachment Image attachment post.
  822. * @param string|array $size Requested size. Image size or array of width and height values
  823. * (in that order). Default 'thumbnail'.
  824. */
  825. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
  826. $attr = array_map( 'esc_attr', $attr );
  827. $html = rtrim("<img $hwstring");
  828. foreach ( $attr as $name => $value ) {
  829. $html .= " $name=" . '"' . $value . '"';
  830. }
  831. $html .= ' />';
  832. }
  833. return $html;
  834. }
  835. /**
  836. * Get the URL of an image attachment.
  837. *
  838. * @since 4.4.0
  839. *
  840. * @param int $attachment_id Image attachment ID.
  841. * @param string|array $size Optional. Image size to retrieve. Accepts any valid image size, or an array
  842. * of width and height values in pixels (in that order). Default 'thumbnail'.
  843. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  844. * @return string|false Attachment URL or false if no image is available.
  845. */
  846. function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
  847. $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
  848. return isset( $image['0'] ) ? $image['0'] : false;
  849. }
  850. /**
  851. * Get the attachment path relative to the upload directory.
  852. *
  853. * @since 4.4.1
  854. * @access private
  855. *
  856. * @param string $file Attachment file name.
  857. * @return string Attachment path relative to the upload directory.
  858. */
  859. function _wp_get_attachment_relative_path( $file ) {
  860. $dirname = dirname( $file );
  861. if ( '.' === $dirname ) {
  862. return '';
  863. }
  864. if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
  865. // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads)
  866. $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
  867. $dirname = ltrim( $dirname, '/' );
  868. }
  869. return $dirname;
  870. }
  871. /**
  872. * Get the image size as array from its meta data.
  873. *
  874. * Used for responsive images.
  875. *
  876. * @since 4.4.0
  877. * @access private
  878. *
  879. * @param string $size_name Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
  880. * @param array $image_meta The image meta data.
  881. * @return array|bool Array of width and height values in pixels (in that order)
  882. * or false if the size doesn't exist.
  883. */
  884. function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
  885. if ( $size_name === 'full' ) {
  886. return array(
  887. absint( $image_meta['width'] ),
  888. absint( $image_meta['height'] ),
  889. );
  890. } elseif ( ! empty( $image_meta['sizes'][$size_name] ) ) {
  891. return array(
  892. absint( $image_meta['sizes'][$size_name]['width'] ),
  893. absint( $image_meta['sizes'][$size_name]['height'] ),
  894. );
  895. }
  896. return false;
  897. }
  898. /**
  899. * Retrieves the value for an image attachment's 'srcset' attribute.
  900. *
  901. * @since 4.4.0
  902. *
  903. * @see wp_calculate_image_srcset()
  904. *
  905. * @param int $attachment_id Image attachment ID.
  906. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of
  907. * width and height values in pixels (in that order). Default 'medium'.
  908. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  909. * Default null.
  910. * @return string|bool A 'srcset' value string or false.
  911. */
  912. function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
  913. if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
  914. return false;
  915. }
  916. if ( ! is_array( $image_meta ) ) {
  917. $image_meta = wp_get_attachment_metadata( $attachment_id );
  918. }
  919. $image_src = $image[0];
  920. $size_array = array(
  921. absint( $image[1] ),
  922. absint( $image[2] )
  923. );
  924. return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
  925. }
  926. /**
  927. * A helper function to calculate the image sources to include in a 'srcset' attribute.
  928. *
  929. * @since 4.4.0
  930. *
  931. * @param array $size_array Array of width and height values in pixels (in that order).
  932. * @param string $image_src The 'src' of the image.
  933. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  934. * @param int $attachment_id Optional. The image attachment ID to pass to the filter. Default 0.
  935. * @return string|bool The 'srcset' attribute value. False on error or when only one source exists.
  936. */
  937. function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
  938. /**
  939. * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
  940. *
  941. * @since 4.5.0
  942. *
  943. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  944. * @param array $size_array Array of width and height values in pixels (in that order).
  945. * @param string $image_src The 'src' of the image.
  946. * @param int $attachment_id The image attachment ID or 0 if not supplied.
  947. */
  948. $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
  949. if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
  950. return false;
  951. }
  952. $image_sizes = $image_meta['sizes'];
  953. // Get the width and height of the image.
  954. $image_width = (int) $size_array[0];
  955. $image_height = (int) $size_array[1];
  956. // Bail early if error/no width.
  957. if ( $image_width < 1 ) {
  958. return false;
  959. }
  960. $image_basename = wp_basename( $image_meta['file'] );
  961. /*
  962. * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
  963. * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
  964. * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
  965. */
  966. if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
  967. $image_sizes[] = array(
  968. 'width' => $image_meta['width'],
  969. 'height' => $image_meta['height'],
  970. 'file' => $image_basename,
  971. );
  972. } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
  973. return false;
  974. }
  975. // Retrieve the uploads sub-directory from the full size image.
  976. $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
  977. if ( $dirname ) {
  978. $dirname = trailingslashit( $dirname );
  979. }
  980. $upload_dir = wp_get_upload_dir();
  981. $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
  982. /*
  983. * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
  984. * (which is to say, when they share the domain name of the current request).
  985. */
  986. if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
  987. $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
  988. }
  989. /*
  990. * Images that have been edited in WordPress after being uploaded will
  991. * contain a unique hash. Look for that hash and use it later to filter
  992. * out images that are leftovers from previous versions.
  993. */
  994. $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
  995. /**
  996. * Filters the maximum image width to be included in a 'srcset' attribute.
  997. *
  998. * @since 4.4.0
  999. *
  1000. * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.
  1001. * @param array $size_array Array of width and height values in pixels (in that order).
  1002. */
  1003. $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
  1004. // Array to hold URL candidates.
  1005. $sources = array();
  1006. /**
  1007. * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
  1008. * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
  1009. * an incorrect image. See #35045.
  1010. */
  1011. $src_matched = false;
  1012. /*
  1013. * Loop through available images. Only use images that are resized
  1014. * versions of the same edit.
  1015. */
  1016. foreach ( $image_sizes as $image ) {
  1017. $is_src = false;
  1018. // Check if image meta isn't corrupted.
  1019. if ( ! is_array( $image ) ) {
  1020. continue;
  1021. }
  1022. // If the file name is part of the `src`, we've confirmed a match.
  1023. if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
  1024. $src_matched = $is_src = true;
  1025. }
  1026. // Filter out images that are from previous edits.
  1027. if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
  1028. continue;
  1029. }
  1030. /*
  1031. * Filters out images that are wider than '$max_srcset_image_width' unless
  1032. * that file is in the 'src' attribute.
  1033. */
  1034. if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
  1035. continue;
  1036. }
  1037. // If the image dimensions are within 1px of the expected size, use it.
  1038. if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
  1039. // Add the URL, descriptor, and value to the sources array to be returned.
  1040. $source = array(
  1041. 'url' => $image_baseurl . $image['file'],
  1042. 'descriptor' => 'w',
  1043. 'value' => $image['width'],
  1044. );
  1045. // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
  1046. if ( $is_src ) {
  1047. $sources = array( $image['width'] => $source ) + $sources;
  1048. } else {
  1049. $sources[ $image['width'] ] = $source;
  1050. }
  1051. }
  1052. }
  1053. /**
  1054. * Filters an image's 'srcset' sources.
  1055. *
  1056. * @since 4.4.0
  1057. *
  1058. * @param array $sources {
  1059. * One or more arrays of source data to include in the 'srcset'.
  1060. *
  1061. * @type array $width {
  1062. * @type string $url The URL of an image source.
  1063. * @type string $descriptor The descriptor type used in the image candidate string,
  1064. * either 'w' or 'x'.
  1065. * @type int $value The source width if paired with a 'w' descriptor, or a
  1066. * pixel density value if paired with an 'x' descriptor.
  1067. * }
  1068. * }
  1069. * @param array $size_array Array of width and height values in pixels (in that order).
  1070. * @param string $image_src The 'src' of the image.
  1071. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1072. * @param int $attachment_id Image attachment ID or 0.
  1073. */
  1074. $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
  1075. // Only return a 'srcset' value if there is more than one source.
  1076. if ( ! $src_matched || count( $sources ) < 2 ) {
  1077. return false;
  1078. }
  1079. $srcset = '';
  1080. foreach ( $sources as $source ) {
  1081. $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
  1082. }
  1083. return rtrim( $srcset, ', ' );
  1084. }
  1085. /**
  1086. * Retrieves the value for an image attachment's 'sizes' attribute.
  1087. *
  1088. * @since 4.4.0
  1089. *
  1090. * @see wp_calculate_image_sizes()
  1091. *
  1092. * @param int $attachment_id Image attachment ID.
  1093. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of width
  1094. * and height values in pixels (in that order). Default 'medium'.
  1095. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1096. * Default null.
  1097. * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
  1098. */
  1099. function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
  1100. if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
  1101. return false;
  1102. }
  1103. if ( ! is_array( $image_meta ) ) {
  1104. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1105. }
  1106. $image_src = $image[0];
  1107. $size_array = array(
  1108. absint( $image[1] ),
  1109. absint( $image[2] )
  1110. );
  1111. return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
  1112. }
  1113. /**
  1114. * Creates a 'sizes' attribute value for an image.
  1115. *
  1116. * @since 4.4.0
  1117. *
  1118. * @param array|string $size Image size to retrieve. Accepts any valid image size, or an array
  1119. * of width and height values in pixels (in that order). Default 'medium'.
  1120. * @param string $image_src Optional. The URL to the image file. Default null.
  1121. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1122. * Default null.
  1123. * @param int $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
  1124. * is needed when using the image size name as argument for `$size`. Default 0.
  1125. * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
  1126. */
  1127. function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
  1128. $width = 0;
  1129. if ( is_array( $size ) ) {
  1130. $width = absint( $size[0] );
  1131. } elseif ( is_string( $size ) ) {
  1132. if ( ! $image_meta && $attachment_id ) {
  1133. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1134. }
  1135. if ( is_array( $image_meta ) ) {
  1136. $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
  1137. if ( $size_array ) {
  1138. $width = absint( $size_array[0] );
  1139. }
  1140. }
  1141. }
  1142. if ( ! $width ) {
  1143. return false;
  1144. }
  1145. // Setup the default 'sizes' attribute.
  1146. $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
  1147. /**
  1148. * Filters the output of 'wp_calculate_image_sizes()'.
  1149. *
  1150. * @since 4.4.0
  1151. *
  1152. * @param string $sizes A source size value for use in a 'sizes' attribute.
  1153. * @param array|string $size Requested size. Image size or array of width and height values
  1154. * in pixels (in that order).
  1155. * @param string|null $image_src The URL to the image file or null.
  1156. * @param array|null $image_meta The image meta data as returned by wp_get_attachment_metadata() or null.
  1157. * @param int $attachment_id Image attachment ID of the original image or 0.
  1158. */
  1159. return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
  1160. }
  1161. /**
  1162. * Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
  1163. *
  1164. * @since 4.4.0
  1165. *
  1166. * @see wp_image_add_srcset_and_sizes()
  1167. *
  1168. * @param string $content The raw post content to be filtered.
  1169. * @return string Converted content with 'srcset' and 'sizes' attributes added to images.
  1170. */
  1171. function wp_make_content_images_responsive( $content ) {
  1172. if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
  1173. return $content;
  1174. }
  1175. $selected_images = $attachment_ids = array();
  1176. foreach( $matches[0] as $image ) {
  1177. if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) &&
  1178. ( $attachment_id = absint( $class_id[1] ) ) ) {
  1179. /*
  1180. * If exactly the same image tag is used more than once, overwrite it.
  1181. * All identical tags will be replaced later with 'str_replace()'.
  1182. */
  1183. $selected_images[ $image ] = $attachment_