PageRenderTime 62ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/media.php

https://github.com/markjaquith/WordPress
PHP | 5374 lines | 2582 code | 643 blank | 2149 comment | 493 complexity | d8284eee926c7cb0ce9fa97279beb5ac MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1

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

Large files files are truncated, but you can click here to view the full file