| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * WordPress API for media display. 4 * 5 * @package WordPress 6 * @subpackage Media 7 */ 8 9 // Don't load directly. 10 if ( ! defined( 'ABSPATH' ) ) { 11 exit; 12 } 13 14 /** 15 * Retrieves additional image sizes. 16 * 17 * @since 4.7.0 18 * 19 * @see add_image_size() 20 * 21 * @global array $_wp_additional_image_sizes 22 * 23 * @return array Additional images size data. 24 * 25 * @phpstan-return array<string, array{ 26 * width: non-negative-int, 27 * height: non-negative-int, 28 * crop: array{ 'left'|'center'|'right', 'top'|'center'|'bottom' }|bool, 29 * }> 30 */ 31 function wp_get_additional_image_sizes() { 32 global $_wp_additional_image_sizes; 33 34 if ( ! $_wp_additional_image_sizes ) { 35 $_wp_additional_image_sizes = array(); 36 } 37 38 return $_wp_additional_image_sizes; 39 } 40 41 /** 42 * Scales down the default size of an image. 43 * 44 * This is so that the image is a better fit for the editor and theme. 45 * 46 * The `$size` parameter accepts either an array or a string. The supported string 47 * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at 48 * 128 width and 96 height in pixels. Also supported for the string value is 49 * 'medium', 'medium_large' and 'full'. The 'full' isn't actually supported, but any value other 50 * than the supported will result in the content_width size or 500 if that is 51 * not set. 52 * 53 * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be 54 * called on the calculated array for width and height, respectively. 55 * 56 * @since 2.5.0 57 * 58 * @global int $content_width 59 * 60 * @param int $width Width of the image in pixels. 61 * @param int $height Height of the image in pixels. 62 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 63 * of width and height values in pixels (in that order). Default 'medium'. 64 * @param string $context Optional. Could be 'display' (like in a theme) or 'edit' 65 * (like inserting into an editor). Default null. 66 * @return int[] { 67 * An array of width and height values. 68 * 69 * @type int $0 The maximum width in pixels. 70 * @type int $1 The maximum height in pixels. 71 * } 72 */ 73 function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) { 74 global $content_width; 75 76 $_wp_additional_image_sizes = wp_get_additional_image_sizes(); 77 78 if ( ! $context ) { 79 $context = is_admin() ? 'edit' : 'display'; 80 } 81 82 if ( is_array( $size ) ) { 83 $max_width = $size[0]; 84 $max_height = $size[1]; 85 } elseif ( 'thumb' === $size || 'thumbnail' === $size ) { 86 $max_width = (int) get_option( 'thumbnail_size_w' ); 87 $max_height = (int) get_option( 'thumbnail_size_h' ); 88 // Last chance thumbnail size defaults. 89 if ( ! $max_width && ! $max_height ) { 90 $max_width = 128; 91 $max_height = 96; 92 } 93 } elseif ( 'medium' === $size ) { 94 $max_width = (int) get_option( 'medium_size_w' ); 95 $max_height = (int) get_option( 'medium_size_h' ); 96 97 } elseif ( 'medium_large' === $size ) { 98 $max_width = (int) get_option( 'medium_large_size_w' ); 99 $max_height = (int) get_option( 'medium_large_size_h' ); 100 101 if ( (int) $content_width > 0 ) { 102 $max_width = min( (int) $content_width, $max_width ); 103 } 104 } elseif ( 'large' === $size ) { 105 /* 106 * We're inserting a large size image into the editor. If it's a really 107 * big image we'll scale it down to fit reasonably within the editor 108 * itself, and within the theme's content width if it's known. The user 109 * can resize it in the editor if they wish. 110 */ 111 $max_width = (int) get_option( 'large_size_w' ); 112 $max_height = (int) get_option( 'large_size_h' ); 113 114 if ( (int) $content_width > 0 ) { 115 $max_width = min( (int) $content_width, $max_width ); 116 } 117 } elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ), true ) ) { 118 $max_width = (int) $_wp_additional_image_sizes[ $size ]['width']; 119 $max_height = (int) $_wp_additional_image_sizes[ $size ]['height']; 120 // Only in admin. Assume that theme authors know what they're doing. 121 if ( (int) $content_width > 0 && 'edit' === $context ) { 122 $max_width = min( (int) $content_width, $max_width ); 123 } 124 } else { // $size === 'full' has no constraint. 125 $max_width = $width; 126 $max_height = $height; 127 } 128 129 /** 130 * Filters the maximum image size dimensions for the editor. 131 * 132 * @since 2.5.0 133 * 134 * @param int[] $max_image_size { 135 * An array of width and height values. 136 * 137 * @type int $0 The maximum width in pixels. 138 * @type int $1 The maximum height in pixels. 139 * } 140 * @param string|int[] $size Requested image size. Can be any registered image size name, or 141 * an array of width and height values in pixels (in that order). 142 * @param string $context The context the image is being resized for. 143 * Possible values are 'display' (like in a theme) 144 * or 'edit' (like inserting into an editor). 145 */ 146 list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context ); 147 148 return wp_constrain_dimensions( $width, $height, $max_width, $max_height ); 149 } 150 151 /** 152 * Retrieves width and height attributes using given width and height values. 153 * 154 * Both attributes are required in the sense that both parameters must have a 155 * value, but are optional in that if you set them to false or null, then they 156 * will not be added to the returned string. 157 * 158 * You can set the value using a string, but it will only take numeric values. 159 * If you wish to put 'px' after the numbers, then it will be stripped out of 160 * the return. 161 * 162 * @since 2.5.0 163 * 164 * @param int|string $width Image width in pixels. 165 * @param int|string $height Image height in pixels. 166 * @return string HTML attributes for width and, or height. 167 */ 168 function image_hwstring( $width, $height ) { 169 $out = ''; 170 if ( $width ) { 171 $out .= 'width="' . (int) $width . '" '; 172 } 173 if ( $height ) { 174 $out .= 'height="' . (int) $height . '" '; 175 } 176 return $out; 177 } 178 179 /** 180 * Scales an image to fit a particular size (such as 'thumb' or 'medium'). 181 * 182 * The URL might be the original image, or it might be a resized version. This 183 * function won't create a new resized copy, it will just return an already 184 * resized one if it exists. 185 * 186 * A plugin may use the {@see 'image_downsize'} filter to hook into and offer image 187 * resizing services for images. The hook must return an array with the same 188 * elements that are normally returned from the function. 189 * 190 * @since 2.5.0 191 * 192 * @param int $id Attachment ID for image. 193 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 194 * of width and height values in pixels (in that order). Default 'medium'. 195 * @return array|false { 196 * Array of image data, or boolean false if no image is available. 197 * 198 * @type string $0 Image source URL. 199 * @type int $1 Image width in pixels. 200 * @type int $2 Image height in pixels. 201 * @type bool $3 Whether the image is a resized image. 202 * } 203 */ 204 function image_downsize( $id, $size = 'medium' ) { 205 $is_image = wp_attachment_is_image( $id ); 206 207 /** 208 * Filters whether to preempt the output of image_downsize(). 209 * 210 * Returning a truthy value from the filter will effectively short-circuit 211 * down-sizing the image, returning that value instead. 212 * 213 * @since 2.5.0 214 * 215 * @param bool|array $downsize Whether to short-circuit the image downsize. 216 * @param int $id Attachment ID for image. 217 * @param string|int[] $size Requested image size. Can be any registered image size name, or 218 * an array of width and height values in pixels (in that order). 219 */ 220 $out = apply_filters( 'image_downsize', false, $id, $size ); 221 222 if ( $out ) { 223 return $out; 224 } 225 226 $img_url = wp_get_attachment_url( $id ); 227 $meta = wp_get_attachment_metadata( $id ); 228 $width = 0; 229 $height = 0; 230 $is_intermediate = false; 231 $img_url_basename = wp_basename( $img_url ); 232 233 /* 234 * If the file isn't an image, attempt to replace its URL with a rendered image from its meta. 235 * Otherwise, a non-image type could be returned. 236 */ 237 if ( ! $is_image ) { 238 if ( ! empty( $meta['sizes']['full'] ) ) { 239 $img_url = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url ); 240 $img_url_basename = $meta['sizes']['full']['file']; 241 $width = $meta['sizes']['full']['width']; 242 $height = $meta['sizes']['full']['height']; 243 } else { 244 return false; 245 } 246 } 247 248 // Try for a new style intermediate size. 249 $intermediate = image_get_intermediate_size( $id, $size ); 250 251 if ( $intermediate ) { 252 $img_url = str_replace( $img_url_basename, $intermediate['file'], $img_url ); 253 $width = $intermediate['width']; 254 $height = $intermediate['height']; 255 $is_intermediate = true; 256 } elseif ( 'thumbnail' === $size && ! empty( $meta['thumb'] ) && is_string( $meta['thumb'] ) ) { 257 // Fall back to the old thumbnail. 258 $imagefile = get_attached_file( $id ); 259 $thumbfile = str_replace( wp_basename( $imagefile ), wp_basename( $meta['thumb'] ), $imagefile ); 260 261 if ( file_exists( $thumbfile ) ) { 262 $info = wp_getimagesize( $thumbfile ); 263 264 if ( $info ) { 265 $img_url = str_replace( $img_url_basename, wp_basename( $thumbfile ), $img_url ); 266 $width = $info[0]; 267 $height = $info[1]; 268 $is_intermediate = true; 269 } 270 } 271 } 272 273 if ( ! $width && ! $height && isset( $meta['width'], $meta['height'] ) ) { 274 // Any other type: use the real image. 275 $width = $meta['width']; 276 $height = $meta['height']; 277 } 278 279 if ( $img_url ) { 280 // We have the actual image size, but might need to further constrain it if content_width is narrower. 281 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size ); 282 283 return array( $img_url, $width, $height, $is_intermediate ); 284 } 285 286 return false; 287 } 288 289 /** 290 * Registers a new image size. 291 * 292 * @since 2.9.0 293 * 294 * @global array $_wp_additional_image_sizes Associative array of additional image sizes. 295 * 296 * @param string $name Image size identifier. 297 * @param int $width Optional. Image width in pixels. Default 0. 298 * @param int $height Optional. Image height in pixels. Default 0. 299 * @param bool|array $crop { 300 * Optional. Image cropping behavior. If false, the image will be scaled (default). 301 * If true, image will be cropped to the specified dimensions using center positions. 302 * If an array, the image will be cropped using the array to specify the crop location: 303 * 304 * @type string $0 The x crop position. Accepts 'left', 'center', or 'right'. 305 * @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'. 306 * } 307 * 308 * @phpstan-param non-negative-int $width 309 * @phpstan-param non-negative-int $height 310 * @phpstan-param array{ 'left'|'center'|'right', 'top'|'center'|'bottom' }|bool $crop 311 */ 312 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) { 313 global $_wp_additional_image_sizes; 314 315 $_wp_additional_image_sizes[ $name ] = array( 316 'width' => absint( $width ), 317 'height' => absint( $height ), 318 'crop' => $crop, 319 ); 320 } 321 322 /** 323 * Checks if an image size exists. 324 * 325 * @since 3.9.0 326 * 327 * @param string $name The image size to check. 328 * @return bool True if the image size exists, false if not. 329 */ 330 function has_image_size( $name ) { 331 $sizes = wp_get_additional_image_sizes(); 332 return isset( $sizes[ $name ] ); 333 } 334 335 /** 336 * Removes a new image size. 337 * 338 * @since 3.9.0 339 * 340 * @global array $_wp_additional_image_sizes 341 * 342 * @param string $name The image size to remove. 343 * @return bool True if the image size was successfully removed, false on failure. 344 */ 345 function remove_image_size( $name ) { 346 global $_wp_additional_image_sizes; 347 348 if ( isset( $_wp_additional_image_sizes[ $name ] ) ) { 349 unset( $_wp_additional_image_sizes[ $name ] ); 350 return true; 351 } 352 353 return false; 354 } 355 356 /** 357 * Registers an image size for the post thumbnail. 358 * 359 * @since 2.9.0 360 * 361 * @see add_image_size() for details on cropping behavior. 362 * 363 * @param int $width Image width in pixels. 364 * @param int $height Image height in pixels. 365 * @param bool|array $crop { 366 * Optional. Image cropping behavior. If false, the image will be scaled (default). 367 * If true, image will be cropped to the specified dimensions using center positions. 368 * If an array, the image will be cropped using the array to specify the crop location: 369 * 370 * @type string $0 The x crop position. Accepts 'left', 'center', or 'right'. 371 * @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'. 372 * } 373 */ 374 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) { 375 add_image_size( 'post-thumbnail', $width, $height, $crop ); 376 } 377 378 /** 379 * Gets an img tag for an image attachment, scaling it down if requested. 380 * 381 * The {@see 'get_image_tag_class'} filter allows for changing the class name for the 382 * image without having to use regular expressions on the HTML content. The 383 * parameters are: what WordPress will use for the class, the Attachment ID, 384 * image align value, and the size the image should be. 385 * 386 * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be 387 * further manipulated by a plugin to change all attribute values and even HTML 388 * content. 389 * 390 * @since 2.5.0 391 * 392 * @param int $id Attachment ID. 393 * @param string $alt Image description for the alt attribute. 394 * @param string $title Image description for the title attribute. 395 * @param string $align Part of the class name for aligning the image. 396 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of 397 * width and height values in pixels (in that order). Default 'medium'. 398 * @return string HTML IMG element for given image attachment. 399 */ 400 function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) { 401 402 list( $img_src, $width, $height ) = image_downsize( $id, $size ); 403 $hwstring = image_hwstring( $width, $height ); 404 405 $title = $title ? 'title="' . esc_attr( $title ) . '" ' : ''; 406 407 $size_class = is_array( $size ) ? implode( 'x', $size ) : $size; 408 $class = 'align' . esc_attr( $align ) . ' size-' . esc_attr( $size_class ) . ' wp-image-' . $id; 409 410 /** 411 * Filters the value of the attachment's image tag class attribute. 412 * 413 * @since 2.6.0 414 * 415 * @param string $class CSS class name or space-separated list of classes. 416 * @param int $id Attachment ID. 417 * @param string $align Part of the class name for aligning the image. 418 * @param string|int[] $size Requested image size. Can be any registered image size name, or 419 * an array of width and height values in pixels (in that order). 420 */ 421 $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size ); 422 423 $html = '<img src="' . esc_url( $img_src ) . '" alt="' . esc_attr( $alt ) . '" ' . $title . $hwstring . 'class="' . $class . '" />'; 424 425 /** 426 * Filters the HTML content for the image tag. 427 * 428 * @since 2.6.0 429 * 430 * @param string $html HTML content for the image. 431 * @param int $id Attachment ID. 432 * @param string $alt Image description for the alt attribute. 433 * @param string $title Image description for the title attribute. 434 * @param string $align Part of the class name for aligning the image. 435 * @param string|int[] $size Requested image size. Can be any registered image size name, or 436 * an array of width and height values in pixels (in that order). 437 */ 438 return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size ); 439 } 440 441 /** 442 * Calculates the new dimensions for a down-sampled image. 443 * 444 * If either width or height are empty, no constraint is applied on 445 * that dimension. 446 * 447 * @since 2.5.0 448 * 449 * @param int $current_width Current width of the image. 450 * @param int $current_height Current height of the image. 451 * @param int $max_width Optional. Max width in pixels to constrain to. Default 0. 452 * @param int $max_height Optional. Max height in pixels to constrain to. Default 0. 453 * @return int[] { 454 * An array of width and height values. 455 * 456 * @type int $0 The width in pixels. 457 * @type int $1 The height in pixels. 458 * } 459 */ 460 function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) { 461 if ( ! $max_width && ! $max_height ) { 462 return array( $current_width, $current_height ); 463 } 464 465 $width_ratio = 1.0; 466 $height_ratio = 1.0; 467 $did_width = false; 468 $did_height = false; 469 470 if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) { 471 $width_ratio = $max_width / $current_width; 472 $did_width = true; 473 } 474 475 if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) { 476 $height_ratio = $max_height / $current_height; 477 $did_height = true; 478 } 479 480 // Calculate the larger/smaller ratios. 481 $smaller_ratio = min( $width_ratio, $height_ratio ); 482 $larger_ratio = max( $width_ratio, $height_ratio ); 483 484 if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) { 485 // The larger ratio is too big. It would result in an overflow. 486 $ratio = $smaller_ratio; 487 } else { 488 // The larger ratio fits, and is likely to be a more "snug" fit. 489 $ratio = $larger_ratio; 490 } 491 492 // Very small dimensions may result in 0, 1 should be the minimum. 493 $w = max( 1, (int) round( $current_width * $ratio ) ); 494 $h = max( 1, (int) round( $current_height * $ratio ) ); 495 496 /* 497 * Sometimes, due to rounding, we'll end up with a result like this: 498 * 465x700 in a 177x177 box is 117x176... a pixel short. 499 * We also have issues with recursive calls resulting in an ever-changing result. 500 * Constraining to the result of a constraint should yield the original result. 501 * Thus we look for dimensions that are one pixel shy of the max value and bump them up. 502 */ 503 504 // Note: $did_width means it is possible $smaller_ratio == $width_ratio. 505 if ( $did_width && $w === $max_width - 1 ) { 506 $w = $max_width; // Round it up. 507 } 508 509 // Note: $did_height means it is possible $smaller_ratio == $height_ratio. 510 if ( $did_height && $h === $max_height - 1 ) { 511 $h = $max_height; // Round it up. 512 } 513 514 /** 515 * Filters dimensions to constrain down-sampled images to. 516 * 517 * @since 4.1.0 518 * 519 * @param int[] $dimensions { 520 * An array of width and height values. 521 * 522 * @type int $0 The width in pixels. 523 * @type int $1 The height in pixels. 524 * } 525 * @param int $current_width The current width of the image. 526 * @param int $current_height The current height of the image. 527 * @param int $max_width The maximum width permitted. 528 * @param int $max_height The maximum height permitted. 529 */ 530 return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height ); 531 } 532 533 /** 534 * Retrieves calculated resize dimensions for use in WP_Image_Editor. 535 * 536 * Calculates dimensions and coordinates for a resized image that fits 537 * within a specified width and height. 538 * 539 * @since 2.5.0 540 * 541 * @param int $orig_w Original width in pixels. 542 * @param int $orig_h Original height in pixels. 543 * @param int $dest_w New width in pixels. 544 * @param int $dest_h New height in pixels. 545 * @param bool|array $crop { 546 * Optional. Image cropping behavior. If false, the image will be scaled (default). 547 * If true, image will be cropped to the specified dimensions using center positions. 548 * If an array, the image will be cropped using the array to specify the crop location: 549 * 550 * @type string $0 The x crop position. Accepts 'left', 'center', or 'right'. 551 * @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'. 552 * } 553 * @return array|false Returned array matches parameters for `imagecopyresampled()`. False on failure. 554 */ 555 function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) { 556 557 if ( $orig_w <= 0 || $orig_h <= 0 ) { 558 return false; 559 } 560 // At least one of $dest_w or $dest_h must be specific. 561 if ( $dest_w <= 0 && $dest_h <= 0 ) { 562 return false; 563 } 564 565 /** 566 * Filters whether to preempt calculating the image resize dimensions. 567 * 568 * Returning a non-null value from the filter will effectively short-circuit 569 * image_resize_dimensions(), returning that value instead. 570 * 571 * @since 3.4.0 572 * 573 * @param null|mixed $null Whether to preempt output of the resize dimensions. 574 * @param int $orig_w Original width in pixels. 575 * @param int $orig_h Original height in pixels. 576 * @param int $dest_w New width in pixels. 577 * @param int $dest_h New height in pixels. 578 * @param bool|array $crop Whether to crop image to specified width and height or resize. 579 * An array can specify positioning of the crop area. Default false. 580 */ 581 $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop ); 582 583 if ( null !== $output ) { 584 return $output; 585 } 586 587 // Stop if the destination size is larger than the original image dimensions. 588 if ( empty( $dest_h ) ) { 589 if ( $orig_w < $dest_w ) { 590 return false; 591 } 592 } elseif ( empty( $dest_w ) ) { 593 if ( $orig_h < $dest_h ) { 594 return false; 595 } 596 } else { 597 if ( $orig_w < $dest_w && $orig_h < $dest_h ) { 598 return false; 599 } 600 } 601 602 if ( $crop ) { 603 /* 604 * Crop the largest possible portion of the original image that we can size to $dest_w x $dest_h. 605 * Note that the requested crop dimensions are used as a maximum bounding box for the original image. 606 * If the original image's width or height is less than the requested width or height 607 * only the greater one will be cropped. 608 * For example when the original image is 600x300, and the requested crop dimensions are 400x400, 609 * the resulting image will be 400x300. 610 */ 611 $aspect_ratio = $orig_w / $orig_h; 612 $new_w = min( $dest_w, $orig_w ); 613 $new_h = min( $dest_h, $orig_h ); 614 615 if ( ! $new_w ) { 616 $new_w = (int) round( $new_h * $aspect_ratio ); 617 } 618 619 if ( ! $new_h ) { 620 $new_h = (int) round( $new_w / $aspect_ratio ); 621 } 622 623 $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h ); 624 625 $crop_w = round( $new_w / $size_ratio ); 626 $crop_h = round( $new_h / $size_ratio ); 627 628 if ( ! is_array( $crop ) || count( $crop ) !== 2 ) { 629 $crop = array( 'center', 'center' ); 630 } 631 632 list( $x, $y ) = $crop; 633 634 if ( 'left' === $x ) { 635 $s_x = 0; 636 } elseif ( 'right' === $x ) { 637 $s_x = $orig_w - $crop_w; 638 } else { 639 $s_x = floor( ( $orig_w - $crop_w ) / 2 ); 640 } 641 642 if ( 'top' === $y ) { 643 $s_y = 0; 644 } elseif ( 'bottom' === $y ) { 645 $s_y = $orig_h - $crop_h; 646 } else { 647 $s_y = floor( ( $orig_h - $crop_h ) / 2 ); 648 } 649 } else { 650 // Resize using $dest_w x $dest_h as a maximum bounding box. 651 $crop_w = $orig_w; 652 $crop_h = $orig_h; 653 654 $s_x = 0; 655 $s_y = 0; 656 657 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h ); 658 } 659 660 if ( wp_fuzzy_number_match( $new_w, $orig_w ) && wp_fuzzy_number_match( $new_h, $orig_h ) ) { 661 // The new size has virtually the same dimensions as the original image. 662 663 /** 664 * Filters whether to proceed with making an image sub-size with identical dimensions 665 * with the original/source image. Differences of 1px may be due to rounding and are ignored. 666 * 667 * @since 5.3.0 668 * 669 * @param bool $proceed The filtered value. 670 * @param int $orig_w Original image width. 671 * @param int $orig_h Original image height. 672 */ 673 $proceed = (bool) apply_filters( 'wp_image_resize_identical_dimensions', false, $orig_w, $orig_h ); 674 675 if ( ! $proceed ) { 676 return false; 677 } 678 } 679 680 /* 681 * The return array matches the parameters to imagecopyresampled(). 682 * int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h 683 */ 684 return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h ); 685 } 686 687 /** 688 * Resizes an image to make a thumbnail or intermediate size. 689 * 690 * The returned array has the file size, the image width, and image height. The 691 * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the 692 * values of the returned array. The only parameter is the resized file path. 693 * 694 * @since 2.5.0 695 * 696 * @param string $file File path. 697 * @param int $width Image width. 698 * @param int $height Image height. 699 * @param bool|array $crop { 700 * Optional. Image cropping behavior. If false, the image will be scaled (default). 701 * If true, image will be cropped to the specified dimensions using center positions. 702 * If an array, the image will be cropped using the array to specify the crop location: 703 * 704 * @type string $0 The x crop position. Accepts 'left', 'center', or 'right'. 705 * @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'. 706 * } 707 * @return array|false Metadata array on success. False if no image was created. 708 */ 709 function image_make_intermediate_size( $file, $width, $height, $crop = false ) { 710 if ( $width || $height ) { 711 $editor = wp_get_image_editor( $file ); 712 713 if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) { 714 return false; 715 } 716 717 $resized_file = $editor->save(); 718 719 if ( ! is_wp_error( $resized_file ) && $resized_file ) { 720 unset( $resized_file['path'] ); 721 return $resized_file; 722 } 723 } 724 return false; 725 } 726 727 /** 728 * Helper function to test if aspect ratios for two images match. 729 * 730 * @since 4.6.0 731 * 732 * @param int $source_width Width of the first image in pixels. 733 * @param int $source_height Height of the first image in pixels. 734 * @param int $target_width Width of the second image in pixels. 735 * @param int $target_height Height of the second image in pixels. 736 * @return bool True if aspect ratios match within 1px. False if not. 737 */ 738 function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) { 739 /* 740 * To test for varying crops, we constrain the dimensions of the larger image 741 * to the dimensions of the smaller image and see if they match. 742 */ 743 if ( $source_width > $target_width ) { 744 $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width ); 745 $expected_size = array( $target_width, $target_height ); 746 } else { 747 $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width ); 748 $expected_size = array( $source_width, $source_height ); 749 } 750 751 // If the image dimensions are within 1px of the expected size, we consider it a match. 752 $matched = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) ); 753 754 return $matched; 755 } 756 757 /** 758 * Retrieves the image's intermediate size (resized) path, width, and height. 759 * 760 * The $size parameter can be an array with the width and height respectively. 761 * If the size matches the 'sizes' metadata array for width and height, then it 762 * will be used. If there is no direct match, then the nearest image size larger 763 * than the specified size will be used. If nothing is found, then the function 764 * will break out and return false. 765 * 766 * The metadata 'sizes' is used for compatible sizes that can be used for the 767 * parameter $size value. 768 * 769 * The url path will be given, when the $size parameter is a string. 770 * 771 * If you are passing an array for the $size, you should consider using 772 * add_image_size() so that a cropped version is generated. It's much more 773 * efficient than having to find the closest-sized image and then having the 774 * browser scale down the image. 775 * 776 * @since 2.5.0 777 * 778 * @param int $post_id Attachment ID. 779 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 780 * of width and height values in pixels (in that order). Default 'thumbnail'. 781 * @return array|false { 782 * Array of file relative path, width, and height on success. Additionally includes absolute 783 * path and URL if registered size is passed to `$size` parameter. False on failure. 784 * 785 * @type string $file Filename of image. 786 * @type int $width Width of image in pixels. 787 * @type int $height Height of image in pixels. 788 * @type string $path Path of image relative to uploads directory. 789 * @type string $url URL of image. 790 * } 791 */ 792 function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) { 793 $imagedata = wp_get_attachment_metadata( $post_id ); 794 795 if ( ! $size || ! is_array( $imagedata ) || empty( $imagedata['sizes'] ) ) { 796 return false; 797 } 798 799 $data = array(); 800 801 // Find the best match when '$size' is an array. 802 if ( is_array( $size ) ) { 803 $candidates = array(); 804 805 if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) { 806 $imagedata['height'] = $imagedata['sizes']['full']['height']; 807 $imagedata['width'] = $imagedata['sizes']['full']['width']; 808 } 809 810 foreach ( $imagedata['sizes'] as $_size => $data ) { 811 // If there's an exact match to an existing image size, short circuit. 812 if ( (int) $data['width'] === (int) $size[0] && (int) $data['height'] === (int) $size[1] ) { 813 $candidates[ $data['width'] * $data['height'] ] = $data; 814 break; 815 } 816 817 // If it's not an exact match, consider larger sizes with the same aspect ratio. 818 if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) { 819 // If '0' is passed to either size, we test ratios against the original file. 820 if ( 0 === $size[0] || 0 === $size[1] ) { 821 $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] ); 822 } else { 823 $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] ); 824 } 825 826 if ( $same_ratio ) { 827 $candidates[ $data['width'] * $data['height'] ] = $data; 828 } 829 } 830 } 831 832 if ( ! empty( $candidates ) ) { 833 // Sort the array by size if we have more than one candidate. 834 if ( 1 < count( $candidates ) ) { 835 ksort( $candidates ); 836 } 837 838 $data = array_shift( $candidates ); 839 } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) 840 && $size[0] <= $imagedata['sizes']['thumbnail']['width'] 841 && $size[1] <= $imagedata['sizes']['thumbnail']['width'] 842 ) { 843 /* 844 * When the size requested is smaller than the thumbnail dimensions, we 845 * fall back to the thumbnail size to maintain backward compatibility with 846 * pre-4.6 versions of WordPress. 847 */ 848 $data = $imagedata['sizes']['thumbnail']; 849 } else { 850 return false; 851 } 852 853 // Constrain the width and height attributes to the requested values. 854 list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size ); 855 856 } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) { 857 $data = $imagedata['sizes'][ $size ]; 858 } 859 860 // If we still don't have a match at this point, return false. 861 if ( empty( $data ) ) { 862 return false; 863 } 864 865 // Include the full filesystem path of the intermediate file. 866 if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) { 867 $file_url = wp_get_attachment_url( $post_id ); 868 $data['path'] = path_join( dirname( $imagedata['file'] ), $data['file'] ); 869 $data['url'] = path_join( dirname( $file_url ), $data['file'] ); 870 } 871 872 /** 873 * Filters the output of image_get_intermediate_size() 874 * 875 * @since 4.4.0 876 * 877 * @see image_get_intermediate_size() 878 * 879 * @param array $data Array of file relative path, width, and height on success. May also include 880 * file absolute path and URL. 881 * @param int $post_id The ID of the image attachment. 882 * @param string|int[] $size Requested image size. Can be any registered image size name, or 883 * an array of width and height values in pixels (in that order). 884 */ 885 return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size ); 886 } 887 888 /** 889 * Gets the available intermediate image size names. 890 * 891 * @since 3.0.0 892 * 893 * @return string[] An array of image size names. 894 */ 895 function get_intermediate_image_sizes() { 896 $default_sizes = array( 'thumbnail', 'medium', 'medium_large', 'large' ); 897 $additional_sizes = wp_get_additional_image_sizes(); 898 899 if ( ! empty( $additional_sizes ) ) { 900 $default_sizes = array_merge( $default_sizes, array_keys( $additional_sizes ) ); 901 } 902 903 /** 904 * Filters the list of intermediate image sizes. 905 * 906 * @since 2.5.0 907 * 908 * @param string[] $default_sizes An array of intermediate image size names. Defaults 909 * are 'thumbnail', 'medium', 'medium_large', 'large'. 910 */ 911 return apply_filters( 'intermediate_image_sizes', $default_sizes ); 912 } 913 914 /** 915 * Returns a normalized list of all currently registered image sub-sizes. 916 * 917 * @since 5.3.0 918 * @uses wp_get_additional_image_sizes() 919 * @uses get_intermediate_image_sizes() 920 * 921 * @return array[] Associative array of arrays of image sub-size information, 922 * keyed by image size name. 923 * 924 * @phpstan-return array<string, array{ 925 * width: non-negative-int, 926 * height: non-negative-int, 927 * crop: array{ 'left'|'center'|'right', 'top'|'center'|'bottom' }|bool, 928 * }> 929 */ 930 function wp_get_registered_image_subsizes(): array { 931 $additional_sizes = wp_get_additional_image_sizes(); 932 $all_sizes = array(); 933 934 foreach ( get_intermediate_image_sizes() as $size_name ) { 935 $size_data = array( 936 'width' => 0, 937 'height' => 0, 938 'crop' => false, 939 ); 940 941 if ( isset( $additional_sizes[ $size_name ]['width'] ) ) { 942 // For sizes added by plugins and themes. 943 $size_data['width'] = (int) $additional_sizes[ $size_name ]['width']; 944 } else { 945 // For default sizes set in options. 946 $size_data['width'] = (int) get_option( "{$size_name}_size_w" ); 947 } 948 949 if ( isset( $additional_sizes[ $size_name ]['height'] ) ) { 950 $size_data['height'] = (int) $additional_sizes[ $size_name ]['height']; 951 } else { 952 $size_data['height'] = (int) get_option( "{$size_name}_size_h" ); 953 } 954 955 if ( empty( $size_data['width'] ) && empty( $size_data['height'] ) ) { 956 // This size isn't set. 957 continue; 958 } 959 960 if ( isset( $additional_sizes[ $size_name ]['crop'] ) ) { 961 $size_data['crop'] = $additional_sizes[ $size_name ]['crop']; 962 } else { 963 $size_data['crop'] = get_option( "{$size_name}_crop" ); 964 } 965 966 if ( ! is_array( $size_data['crop'] ) || empty( $size_data['crop'] ) ) { 967 $size_data['crop'] = (bool) $size_data['crop']; 968 } 969 970 $all_sizes[ $size_name ] = $size_data; 971 } 972 973 return $all_sizes; 974 } 975 976 /** 977 * Determines the encode quality WordPress would use for an image. 978 * 979 * Resolves the quality the same way WP_Image_Editor::set_quality() does when no 980 * explicit quality is supplied: it starts from the per-format default, applies the 981 * 'wp_editor_set_quality' filter, then the 'jpeg_quality' filter for JPEG output, 982 * resets out-of-range values to the per-format default, and squashes 0 to 1. 983 * 984 * This lets code outside of an image editor instance - such as the REST API, which 985 * reports the quality client-side processing should use - resolve the same value the 986 * server would apply, without loading the image into an editor. 987 * 988 * @since 7.1.0 989 * 990 * @param string $mime_type The output image MIME type, e.g. 'image/jpeg'. 991 * @param array $size { 992 * Optional. Dimensions of the image, passed to the 'wp_editor_set_quality' filter. 993 * 994 * @type int $width The image width in pixels. 995 * @type int $height The image height in pixels. 996 * } 997 * @param int|null $default_quality Optional. Starting quality before filters are applied. 998 * Defaults to the per-format default (86 for WebP, 82 otherwise). 999 * @return int Encode quality between 1 and 100. 1000 * 1001 * @phpstan-param non-empty-string $mime_type 1002 * @phpstan-param array{ width?: non-negative-int, height?: non-negative-int } $size 1003 * @phpstan-param int<0, 100>|null $default_quality 1004 * @phpstan-return int<1, 100> 1005 */ 1006 function wp_get_image_encode_quality( string $mime_type, array $size = array(), ?int $default_quality = null ): int { 1007 if ( null === $default_quality ) { 1008 // Mirror WP_Image_Editor::get_default_quality(): WebP defaults to 86, everything else to 82. 1009 $default_quality = ( 'image/webp' === $mime_type ) ? 86 : 82; 1010 } 1011 1012 /** This filter is documented in wp-includes/class-wp-image-editor.php */ 1013 $quality = apply_filters( 'wp_editor_set_quality', $default_quality, $mime_type, $size ); 1014 1015 if ( 'image/jpeg' === $mime_type ) { 1016 /** This filter is documented in wp-includes/class-wp-image-editor.php */ 1017 $quality = apply_filters( 'jpeg_quality', $quality, 'image_resize' ); 1018 } 1019 1020 if ( ! is_numeric( $quality ) ) { 1021 $quality = $default_quality; 1022 } else { 1023 $quality = (int) $quality; 1024 } 1025 1026 // Reset out-of-range values to the default, matching WP_Image_Editor::set_quality(). 1027 if ( $quality < 0 || $quality > 100 ) { 1028 $quality = $default_quality; 1029 } 1030 1031 // Allow 0, but squash to 1, matching WP_Image_Editor::set_quality(). 1032 if ( 0 === $quality ) { 1033 $quality = 1; 1034 } 1035 1036 return $quality; 1037 } 1038 1039 /** 1040 * Retrieves an image to represent an attachment. 1041 * 1042 * @since 2.5.0 1043 * 1044 * @param int $attachment_id Image attachment ID. 1045 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of 1046 * width and height values in pixels (in that order). Default 'thumbnail'. 1047 * @param bool $icon Optional. Whether the image should fall back to a mime type icon. Default false. 1048 * @return array|false { 1049 * Array of image data, or boolean false if no image is available. 1050 * 1051 * @type string $0 Image source URL. 1052 * @type int $1 Image width in pixels. 1053 * @type int $2 Image height in pixels. 1054 * @type bool $3 Whether the image is a resized image. 1055 * } 1056 * @phpstan-return array{ 0: string, 1: int, 2: int, 3: bool }|false 1057 */ 1058 function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) { 1059 // Get a thumbnail or intermediate image if there is one. 1060 $image = image_downsize( $attachment_id, $size ); 1061 if ( ! $image ) { 1062 $src = false; 1063 $width = 0; 1064 $height = 0; 1065 1066 if ( $icon ) { 1067 $src = wp_mime_type_icon( $attachment_id, '.svg' ); 1068 1069 if ( $src ) { 1070 /** This filter is documented in wp-includes/post.php */ 1071 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' ); 1072 1073 $src_file = $icon_dir . '/' . wp_basename( $src ); 1074 1075 $image_size = wp_getimagesize( $src_file ); 1076 if ( is_array( $image_size ) ) { 1077 $width = $image_size[0]; 1078 $height = $image_size[1]; 1079 } 1080 1081 $ext = strtolower( substr( $src_file, -4 ) ); 1082 1083 if ( '.svg' === $ext ) { 1084 // SVG does not have true dimensions, so this assigns width and height directly. 1085 $width = 48; 1086 $height = 64; 1087 } else { 1088 $image_size = wp_getimagesize( $src_file ); 1089 if ( is_array( $image_size ) ) { 1090 $width = $image_size[0]; 1091 $height = $image_size[1]; 1092 } 1093 } 1094 } 1095 } 1096 1097 if ( $src && $width && $height ) { 1098 $image = array( $src, $width, $height, false ); 1099 } 1100 } 1101 /** 1102 * Filters the attachment image source result. 1103 * 1104 * @since 4.3.0 1105 * 1106 * @param array|false $image { 1107 * Array of image data, or boolean false if no image is available. 1108 * 1109 * @type string $0 Image source URL. 1110 * @type int $1 Image width in pixels. 1111 * @type int $2 Image height in pixels. 1112 * @type bool $3 Whether the image is a resized image. 1113 * } 1114 * @param int $attachment_id Image attachment ID. 1115 * @param string|int[] $size Requested image size. Can be any registered image size name, or 1116 * an array of width and height values in pixels (in that order). 1117 * @param bool $icon Whether the image should be treated as an icon. 1118 */ 1119 $source = apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon ); 1120 if ( is_array( $source ) && isset( $source[0] ) && is_string( $source[0] ) ) { 1121 return array( 1122 $source[0], 1123 (int) ( $source[1] ?? 0 ), 1124 (int) ( $source[2] ?? 0 ), 1125 (bool) ( $source[3] ?? false ), 1126 ); 1127 } 1128 return false; 1129 } 1130 1131 /** 1132 * Gets an HTML img element representing an image attachment. 1133 * 1134 * While `$size` will accept an array, it is better to register a size with 1135 * add_image_size() so that a cropped version is generated. It's much more 1136 * efficient than having to find the closest-sized image and then having the 1137 * browser scale down the image. 1138 * 1139 * @since 2.5.0 1140 * @since 4.4.0 The `$srcset` and `$sizes` attributes were added. 1141 * @since 5.5.0 The `$loading` attribute was added. 1142 * @since 6.1.0 The `$decoding` attribute was added. 1143 * 1144 * @param int $attachment_id Image attachment ID. 1145 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 1146 * of width and height values in pixels (in that order). Default 'thumbnail'. 1147 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false. 1148 * @param string|array $attr { 1149 * Optional. Attributes for the image markup. 1150 * 1151 * @type string $src Image attachment URL. 1152 * @type string $class CSS class name or space-separated list of classes. 1153 * Default `attachment-$size_class size-$size_class`, 1154 * where `$size_class` is the image size being requested. 1155 * @type string $alt Image description for the alt attribute. 1156 * @type string $srcset The 'srcset' attribute value. 1157 * @type string $sizes The 'sizes' attribute value. 1158 * @type string|false $loading The 'loading' attribute value. Passing a value of false 1159 * will result in the attribute being omitted for the image. 1160 * Default determined by {@see wp_get_loading_optimization_attributes()}. 1161 * @type string $decoding The 'decoding' attribute value. Possible values are 1162 * 'async' (default), 'sync', or 'auto'. Passing false or an empty 1163 * string will result in the attribute being omitted. 1164 * @type string $fetchpriority The 'fetchpriority' attribute value, whether `high`, `low`, or `auto`. 1165 * Default determined by {@see wp_get_loading_optimization_attributes()}. 1166 * } 1167 * @return string HTML img element or empty string on failure. 1168 */ 1169 function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) { 1170 $html = ''; 1171 $image = wp_get_attachment_image_src( $attachment_id, $size, $icon ); 1172 1173 if ( $image ) { 1174 list( $src, $width, $height ) = $image; 1175 1176 $attachment = get_post( $attachment_id ); 1177 $size_class = $size; 1178 1179 if ( is_array( $size_class ) ) { 1180 $size_class = implode( 'x', $size_class ); 1181 } 1182 1183 $default_attr = array( 1184 'src' => $src, 1185 'class' => "attachment-$size_class size-$size_class", 1186 'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ), 1187 ); 1188 1189 /** 1190 * Filters the context in which wp_get_attachment_image() is used. 1191 * 1192 * @since 6.3.0 1193 * 1194 * @param string $context The context. Default 'wp_get_attachment_image'. 1195 */ 1196 $context = apply_filters( 'wp_get_attachment_image_context', 'wp_get_attachment_image' ); 1197 1198 $attr = wp_parse_args( $attr, $default_attr ); 1199 1200 // Ensure that the `$width` doesn't overwrite an already valid user-provided width. 1201 if ( ! isset( $attr['width'] ) || ! is_numeric( $attr['width'] ) ) { 1202 $attr['width'] = $width; 1203 } 1204 1205 // Ensure that the `$height` doesn't overwrite an already valid user-provided height. 1206 if ( ! isset( $attr['height'] ) || ! is_numeric( $attr['height'] ) ) { 1207 $attr['height'] = $height; 1208 } 1209 1210 $loading_optimization_attr = wp_get_loading_optimization_attributes( 1211 'img', 1212 $attr, 1213 $context 1214 ); 1215 1216 // Add loading optimization attributes if not available. 1217 $attr = array_merge( $attr, $loading_optimization_attr ); 1218 1219 // Omit the `decoding` attribute if the value is invalid according to the spec. 1220 if ( empty( $attr['decoding'] ) || ! in_array( $attr['decoding'], array( 'async', 'sync', 'auto' ), true ) ) { 1221 unset( $attr['decoding'] ); 1222 } 1223 1224 /* 1225 * If the default value of `lazy` for the `loading` attribute is overridden 1226 * to omit the attribute for this image, ensure it is not included. 1227 */ 1228 if ( isset( $attr['loading'] ) && ! $attr['loading'] ) { 1229 unset( $attr['loading'] ); 1230 } 1231 1232 // If the `fetchpriority` attribute is overridden and set to false or an empty string. 1233 if ( isset( $attr['fetchpriority'] ) && ! $attr['fetchpriority'] ) { 1234 unset( $attr['fetchpriority'] ); 1235 } 1236 1237 // Generate 'srcset' and 'sizes' if not already present. 1238 if ( empty( $attr['srcset'] ) ) { 1239 $image_meta = wp_get_attachment_metadata( $attachment_id ); 1240 1241 if ( is_array( $image_meta ) ) { 1242 $size_array = array( absint( $width ), absint( $height ) ); 1243 $srcset = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id ); 1244 $sizes = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id ); 1245 1246 if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) { 1247 $attr['srcset'] = $srcset; 1248 1249 if ( empty( $attr['sizes'] ) ) { 1250 $attr['sizes'] = $sizes; 1251 } 1252 } 1253 } 1254 } 1255 1256 /** This filter is documented in wp-includes/media.php */ 1257 $add_auto_sizes = apply_filters( 'wp_img_tag_add_auto_sizes', true ); 1258 1259 // Adds 'auto' to the sizes attribute if applicable. 1260 if ( 1261 $add_auto_sizes && 1262 isset( $attr['loading'] ) && 1263 'lazy' === $attr['loading'] && 1264 isset( $attr['sizes'] ) && 1265 ! wp_sizes_attribute_includes_valid_auto( $attr['sizes'] ) 1266 ) { 1267 $attr['sizes'] = 'auto, ' . $attr['sizes']; 1268 } 1269 1270 /** 1271 * Filters the list of attachment image attributes. 1272 * 1273 * @since 2.8.0 1274 * @since 6.8.2 The `$attr` array includes `width` and `height` attributes. 1275 * 1276 * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name. 1277 * See wp_get_attachment_image(). 1278 * @param WP_Post $attachment Image attachment post. 1279 * @param string|int[] $size Requested image size. Can be any registered image size name, or 1280 * an array of width and height values in pixels (in that order). 1281 */ 1282 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size ); 1283 1284 if ( isset( $attr['width'] ) && is_numeric( $attr['width'] ) ) { 1285 $width = absint( $attr['width'] ); 1286 } 1287 if ( isset( $attr['height'] ) && is_numeric( $attr['height'] ) ) { 1288 $height = absint( $attr['height'] ); 1289 } 1290 unset( $attr['width'], $attr['height'] ); 1291 1292 $attr = array_map( 'esc_attr', $attr ); 1293 $hwstring = image_hwstring( $width, $height ); 1294 $html = rtrim( "<img $hwstring" ); 1295 1296 foreach ( $attr as $name => $value ) { 1297 $html .= " $name=" . '"' . $value . '"'; 1298 } 1299 1300 $html .= ' />'; 1301 } 1302 1303 /** 1304 * Filters the HTML img element representing an image attachment. 1305 * 1306 * @since 5.6.0 1307 * 1308 * @param string $html HTML img element or empty string on failure. 1309 * @param int $attachment_id Image attachment ID. 1310 * @param string|int[] $size Requested image size. Can be any registered image size name, or 1311 * an array of width and height values in pixels (in that order). 1312 * @param bool $icon Whether the image should be treated as an icon. 1313 * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name. 1314 * See wp_get_attachment_image(). 1315 */ 1316 return apply_filters( 'wp_get_attachment_image', $html, $attachment_id, $size, $icon, $attr ); 1317 } 1318 1319 /** 1320 * Gets the URL of an image attachment. 1321 * 1322 * @since 4.4.0 1323 * 1324 * @param int $attachment_id Image attachment ID. 1325 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of 1326 * width and height values in pixels (in that order). Default 'thumbnail'. 1327 * @param bool $icon Optional. Whether the image should be treated as an icon. Default false. 1328 * @return string|false Attachment URL or false if no image is available. If `$size` does not match 1329 * any registered image size, the original image URL will be returned. 1330 */ 1331 function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) { 1332 $image = wp_get_attachment_image_src( $attachment_id, $size, $icon ); 1333 return $image[0] ?? false; 1334 } 1335 1336 /** 1337 * Gets the attachment path relative to the upload directory. 1338 * 1339 * @since 4.4.1 1340 * @access private 1341 * 1342 * @param string $file Attachment file name. 1343 * @return string Attachment path relative to the upload directory. 1344 */ 1345 function _wp_get_attachment_relative_path( $file ) { 1346 $dirname = dirname( $file ); 1347 1348 if ( '.' === $dirname ) { 1349 return ''; 1350 } 1351 1352 if ( str_contains( $dirname, 'wp-content/uploads' ) ) { 1353 // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads). 1354 $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 ); 1355 $dirname = ltrim( $dirname, '/' ); 1356 } 1357 1358 return $dirname; 1359 } 1360 1361 /** 1362 * Gets the image size as array from its meta data. 1363 * 1364 * Used for responsive images. 1365 * 1366 * @since 4.4.0 1367 * @access private 1368 * 1369 * @param string $size_name Image size. Accepts any registered image size name. 1370 * @param array $image_meta The image meta data. 1371 * @return array|false { 1372 * Array of width and height or false if the size isn't present in the meta data. 1373 * 1374 * @type int $0 Image width. 1375 * @type int $1 Image height. 1376 * } 1377 */ 1378 function _wp_get_image_size_from_meta( $size_name, $image_meta ) { 1379 if ( 'full' === $size_name ) { 1380 return array( 1381 absint( $image_meta['width'] ), 1382 absint( $image_meta['height'] ), 1383 ); 1384 } elseif ( ! empty( $image_meta['sizes'][ $size_name ] ) ) { 1385 return array( 1386 absint( $image_meta['sizes'][ $size_name ]['width'] ), 1387 absint( $image_meta['sizes'][ $size_name ]['height'] ), 1388 ); 1389 } 1390 1391 return false; 1392 } 1393 1394 /** 1395 * Retrieves the value for an image attachment's 'srcset' attribute. 1396 * 1397 * @since 4.4.0 1398 * 1399 * @see wp_calculate_image_srcset() 1400 * 1401 * @param int $attachment_id Image attachment ID. 1402 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of 1403 * width and height values in pixels (in that order). Default 'medium'. 1404 * @param array|null $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'. 1405 * Default null. 1406 * @return string|false A 'srcset' value string or false. 1407 */ 1408 function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) { 1409 $image = wp_get_attachment_image_src( $attachment_id, $size ); 1410 1411 if ( ! $image ) { 1412 return false; 1413 } 1414 1415 if ( ! is_array( $image_meta ) ) { 1416 $image_meta = wp_get_attachment_metadata( $attachment_id ); 1417 } 1418 1419 $image_src = $image[0]; 1420 $size_array = array( 1421 absint( $image[1] ), 1422 absint( $image[2] ), 1423 ); 1424 1425 return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id ); 1426 } 1427 1428 /** 1429 * A helper function to calculate the image sources to include in a 'srcset' attribute. 1430 * 1431 * @since 4.4.0 1432 * 1433 * @param int[] $size_array { 1434 * An array of width and height values. 1435 * 1436 * @type int $0 The width in pixels. 1437 * @type int $1 The height in pixels. 1438 * } 1439 * @param string $image_src The 'src' of the image. 1440 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'. 1441 * @param int $attachment_id Optional. The image attachment ID. Default 0. 1442 * @return string|false The 'srcset' attribute value. False on error or when only one source exists. 1443 */ 1444 function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) { 1445 /** 1446 * Pre-filters the image meta to be able to fix inconsistencies in the stored data. 1447 * 1448 * @since 4.5.0 1449 * 1450 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'. 1451 * @param int[] $size_array { 1452 * An array of requested width and height values. 1453 * 1454 * @type int $0 The width in pixels. 1455 * @type int $1 The height in pixels. 1456 * } 1457 * @param string $image_src The 'src' of the image. 1458 * @param int $attachment_id The image attachment ID or 0 if not supplied. 1459 */ 1460 $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id ); 1461 1462 if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) { 1463 return false; 1464 } 1465 1466 $image_sizes = $image_meta['sizes']; 1467 1468 // Get the width and height of the image. 1469 $image_width = (int) $size_array[0]; 1470 $image_height = (int) $size_array[1]; 1471 1472 // Bail early if error/no width. 1473 if ( $image_width < 1 ) { 1474 return false; 1475 } 1476 1477 $image_basename = wp_basename( $image_meta['file'] ); 1478 1479 /* 1480 * WordPress flattens animated GIFs into one frame when generating intermediate sizes. 1481 * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated. 1482 * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated. 1483 */ 1484 if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) { 1485 $image_sizes[] = array( 1486 'width' => $image_meta['width'], 1487 'height' => $image_meta['height'], 1488 'file' => $image_basename, 1489 ); 1490 } elseif ( str_contains( $image_src, $image_meta['file'] ) ) { 1491 return false; 1492 } 1493 1494 // Retrieve the uploads sub-directory from the full size image. 1495 $dirname = _wp_get_attachment_relative_path( $image_meta['file'] ); 1496 1497 if ( $dirname ) { 1498 $dirname = trailingslashit( $dirname ); 1499 } 1500 1501 $upload_dir = wp_get_upload_dir(); 1502 $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname; 1503 1504 /* 1505 * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain 1506 * (which is to say, when they share the domain name of the current request). 1507 */ 1508 if ( is_ssl() && ! str_starts_with( $image_baseurl, 'https' ) ) { 1509 /* 1510 * Since the `Host:` header might contain a port, it should 1511 * be compared against the image URL using the same port. 1512 */ 1513 $parsed = parse_url( $image_baseurl ); 1514 $domain = $parsed['host'] ?? ''; 1515 1516 if ( isset( $parsed['port'] ) ) { 1517 $domain .= ':' . $parsed['port']; 1518 } 1519 1520 if ( $_SERVER['HTTP_HOST'] === $domain ) { 1521 $image_baseurl = set_url_scheme( $image_baseurl, 'https' ); 1522 } 1523 } 1524 1525 /* 1526 * Images that have been edited in WordPress after being uploaded will 1527 * contain a unique hash. Look for that hash and use it later to filter 1528 * out images that are leftovers from previous versions. 1529 */ 1530 $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash ); 1531 1532 /** 1533 * Filters the maximum image width to be included in a 'srcset' attribute. 1534 * 1535 * @since 4.4.0 1536 * 1537 * @param int $max_width The maximum image width to be included in the 'srcset'. Default '2048'. 1538 * @param int[] $size_array { 1539 * An array of requested width and height values. 1540 * 1541 * @type int $0 The width in pixels. 1542 * @type int $1 The height in pixels. 1543 * } 1544 */ 1545 $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 2048, $size_array ); 1546 1547 // Array to hold URL candidates. 1548 $sources = array(); 1549 1550 /** 1551 * To make sure the ID matches our image src, we will check to see if any sizes in our attachment 1552 * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving 1553 * an incorrect image. See #35045. 1554 */ 1555 $src_matched = false; 1556 1557 /* 1558 * Loop through available images. Only use images that are resized 1559 * versions of the same edit. 1560 */ 1561 foreach ( $image_sizes as $image ) { 1562 $is_src = false; 1563 1564 // Check if image meta isn't corrupted. 1565 if ( ! is_array( $image ) ) { 1566 continue; 1567 } 1568 1569 // If the file name is part of the `src`, we've confirmed a match. 1570 if ( ! $src_matched && str_contains( $image_src, $dirname . $image['file'] ) ) { 1571 $src_matched = true; 1572 $is_src = true; 1573 } 1574 1575 // Filter out images that are from previous edits. 1576 if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) { 1577 continue; 1578 } 1579 1580 /* 1581 * Filters out images that are wider than '$max_srcset_image_width' unless 1582 * that file is in the 'src' attribute. 1583 */ 1584 if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) { 1585 continue; 1586 } 1587 1588 // If the image dimensions are within 1px of the expected size, use it. 1589 if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) { 1590 // Add the URL, descriptor, and value to the sources array to be returned. 1591 $source = array( 1592 'url' => $image_baseurl . $image['file'], 1593 'descriptor' => 'w', 1594 'value' => $image['width'], 1595 ); 1596 1597 // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030. 1598 if ( $is_src ) { 1599 $sources = array( $image['width'] => $source ) + $sources; 1600 } else { 1601 $sources[ $image['width'] ] = $source; 1602 } 1603 } 1604 } 1605 1606 /** 1607 * Filters an image's 'srcset' sources. 1608 * 1609 * @since 4.4.0 1610 * 1611 * @param array $sources { 1612 * One or more arrays of source data to include in the 'srcset'. 1613 * 1614 * @type array $width { 1615 * @type string $url The URL of an image source. 1616 * @type string $descriptor The descriptor type used in the image candidate string, 1617 * either 'w' or 'x'. 1618 * @type int $value The source width if paired with a 'w' descriptor, or a 1619 * pixel density value if paired with an 'x' descriptor. 1620 * } 1621 * } 1622 * @param array $size_array { 1623 * An array of requested width and height values. 1624 * 1625 * @type int $0 The width in pixels. 1626 * @type int $1 The height in pixels. 1627 * } 1628 * @param string $image_src The 'src' of the image. 1629 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'. 1630 * @param int $attachment_id Image attachment ID or 0. 1631 */ 1632 $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id ); 1633 1634 // Only return a 'srcset' value if there is more than one source. 1635 if ( ! $src_matched || ! is_array( $sources ) || count( $sources ) < 2 ) { 1636 return false; 1637 } 1638 1639 $srcset = ''; 1640 1641 foreach ( $sources as $source ) { 1642 $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', '; 1643 } 1644 1645 return rtrim( $srcset, ', ' ); 1646 } 1647 1648 /** 1649 * Retrieves the value for an image attachment's 'sizes' attribute. 1650 * 1651 * @since 4.4.0 1652 * 1653 * @see wp_calculate_image_sizes() 1654 * 1655 * @param int $attachment_id Image attachment ID. 1656 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of 1657 * width and height values in pixels (in that order). Default 'medium'. 1658 * @param array|null $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'. 1659 * Default null. 1660 * @return string|false A valid source size value for use in a 'sizes' attribute or false. 1661 */ 1662 function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) { 1663 $image = wp_get_attachment_image_src( $attachment_id, $size ); 1664 1665 if ( ! $image ) { 1666 return false; 1667 } 1668 1669 if ( ! is_array( $image_meta ) ) { 1670 $image_meta = wp_get_attachment_metadata( $attachment_id ); 1671 } 1672 1673 $image_src = $image[0]; 1674 $size_array = array( 1675 absint( $image[1] ), 1676 absint( $image[2] ), 1677 ); 1678 1679 return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id ); 1680 } 1681 1682 /** 1683 * Creates a 'sizes' attribute value for an image. 1684 * 1685 * @since 4.4.0 1686 * 1687 * @param string|int[] $size Image size. Accepts any registered image size name, or an array of 1688 * width and height values in pixels (in that order). 1689 * @param string|null $image_src Optional. The URL to the image file. Default null. 1690 * @param array|null $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'. 1691 * Default null. 1692 * @param int $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id` 1693 * is needed when using the image size name as argument for `$size`. Default 0. 1694 * @return string|false A valid source size value for use in a 'sizes' attribute or false. 1695 */ 1696 function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) { 1697 $width = 0; 1698 1699 if ( is_array( $size ) ) { 1700 $width = absint( $size[0] ); 1701 } elseif ( is_string( $size ) ) { 1702 if ( ! $image_meta && $attachment_id ) { 1703 $image_meta = wp_get_attachment_metadata( $attachment_id ); 1704 } 1705 1706 if ( is_array( $image_meta ) ) { 1707 $size_array = _wp_get_image_size_from_meta( $size, $image_meta ); 1708 if ( $size_array ) { 1709 $width = absint( $size_array[0] ); 1710 } 1711 } 1712 } 1713 1714 if ( ! $width ) { 1715 return false; 1716 } 1717 1718 // Setup the default 'sizes' attribute. 1719 $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width ); 1720 1721 /** 1722 * Filters the output of wp_calculate_image_sizes(). 1723 * 1724 * @since 4.4.0 1725 * 1726 * @param string $sizes A source size value for use in a 'sizes' attribute. 1727 * @param string|int[] $size Requested image size. Can be any registered image size name, or 1728 * an array of width and height values in pixels (in that order). 1729 * @param string|null $image_src The URL to the image file or null. 1730 * @param array|null $image_meta The image meta data as returned by wp_get_attachment_metadata() or null. 1731 * @param int $attachment_id Image attachment ID of the original image or 0. 1732 */ 1733 return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id ); 1734 } 1735 1736 /** 1737 * Determines if the image meta data is for the image source file. 1738 * 1739 * The image meta data is retrieved by attachment post ID. In some cases the post IDs may change. 1740 * For example when the website is exported and imported at another website. Then the 1741 * attachment post IDs that are in post_content for the exported website may not match 1742 * the same attachments at the new website. 1743 * 1744 * @since 5.5.0 1745 * 1746 * @param string $image_location The full path or URI to the image file. 1747 * @param array $image_meta The attachment meta data as returned by 'wp_get_attachment_metadata()'. 1748 * @param int $attachment_id Optional. The image attachment ID. Default 0. 1749 * @return bool Whether the image meta is for this image file. 1750 */ 1751 function wp_image_file_matches_image_meta( $image_location, $image_meta, $attachment_id = 0 ) { 1752 $match = false; 1753 1754 // Ensure the $image_meta is valid. 1755 if ( isset( $image_meta['file'] ) && strlen( $image_meta['file'] ) > 4 ) { 1756 // Remove query args in image URI. 1757 list( $image_location ) = explode( '?', $image_location ); 1758 1759 // Check if the relative image path from the image meta is at the end of $image_location. 1760 if ( strrpos( $image_location, $image_meta['file'] ) === strlen( $image_location ) - strlen( $image_meta['file'] ) ) { 1761 $match = true; 1762 } else { 1763 // Retrieve the uploads sub-directory from the full size image. 1764 $dirname = _wp_get_attachment_relative_path( $image_meta['file'] ); 1765 1766 if ( $dirname ) { 1767 $dirname = trailingslashit( $dirname ); 1768 } 1769 1770 if ( ! empty( $image_meta['original_image'] ) ) { 1771 $relative_path = $dirname . $image_meta['original_image']; 1772 1773 if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) { 1774 $match = true; 1775 } 1776 } 1777 1778 if ( ! $match && ! empty( $image_meta['sizes'] ) ) { 1779 foreach ( $image_meta['sizes'] as $image_size_data ) { 1780 $relative_path = $dirname . $image_size_data['file']; 1781 1782 if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) { 1783 $match = true; 1784 break; 1785 } 1786 } 1787 } 1788 } 1789 } 1790 1791 /** 1792 * Filters whether an image path or URI matches image meta. 1793 * 1794 * @since 5.5.0 1795 * 1796 * @param bool $match Whether the image relative path from the image meta 1797 * matches the end of the URI or path to the image file. 1798 * @param string $image_location Full path or URI to the tested image file. 1799 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'. 1800 * @param int $attachment_id The image attachment ID or 0 if not supplied. 1801 */ 1802 return apply_filters( 'wp_image_file_matches_image_meta', $match, $image_location, $image_meta, $attachment_id ); 1803 } 1804 1805 /** 1806 * Determines an image's width and height dimensions based on the source file. 1807 * 1808 * @since 5.5.0 1809 * 1810 * @param string $image_src The image source file. 1811 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'. 1812 * @param int $attachment_id Optional. The image attachment ID. Default 0. 1813 * @return array|false Array with first element being the width and second element being the height, 1814 * or false if dimensions cannot be determined. 1815 */ 1816 function wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id = 0 ) { 1817 $dimensions = false; 1818 1819 // Is it a full size image? 1820 if ( 1821 isset( $image_meta['file'] ) && 1822 str_contains( $image_src, wp_basename( $image_meta['file'] ) ) 1823 ) { 1824 $dimensions = array( 1825 (int) $image_meta['width'], 1826 (int) $image_meta['height'], 1827 ); 1828 } 1829 1830 if ( ! $dimensions && ! empty( $image_meta['sizes'] ) ) { 1831 $src_filename = wp_basename( $image_src ); 1832 1833 foreach ( $image_meta['sizes'] as $image_size_data ) { 1834 if ( $src_filename === $image_size_data['file'] ) { 1835 $dimensions = array( 1836 (int) $image_size_data['width'], 1837 (int) $image_size_data['height'], 1838 ); 1839 1840 break; 1841 } 1842 } 1843 } 1844 1845 /** 1846 * Filters the wp_image_src_get_dimensions() value. 1847 * 1848 * @since 5.7.0 1849 * 1850 * @param array|false $dimensions Array with first element being the width 1851 * and second element being the height, or 1852 * false if dimensions could not be determined. 1853 * @param string $image_src The image source file. 1854 * @param array $image_meta The image meta data as returned by 1855 * 'wp_get_attachment_metadata()'. 1856 * @param int $attachment_id The image attachment ID. Default 0. 1857 */ 1858 return apply_filters( 'wp_image_src_get_dimensions', $dimensions, $image_src, $image_meta, $attachment_id ); 1859 } 1860 1861 /** 1862 * Adds 'srcset' and 'sizes' attributes to an existing 'img' element. 1863 * 1864 * @since 4.4.0 1865 * 1866 * @see wp_calculate_image_srcset() 1867 * @see wp_calculate_image_sizes() 1868 * 1869 * @param string $image An HTML 'img' element to be filtered. 1870 * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'. 1871 * @param int $attachment_id Image attachment ID. 1872 * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added. 1873 */ 1874 function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) { 1875 // Ensure the image meta exists. 1876 if ( empty( $image_meta['sizes'] ) ) { 1877 return $image; 1878 } 1879 1880 $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : ''; 1881 list( $image_src ) = explode( '?', $image_src ); 1882 1883 // Return early if we couldn't get the image source. 1884 if ( ! $image_src ) { 1885 return $image; 1886 } 1887 1888 // Bail early if an image has been inserted and later edited. 1889 if ( isset( $image_meta['file'] ) && preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) 1890 && ! str_contains( wp_basename( $image_src ), $img_edit_hash[0] ) 1891 ) { 1892 return $image; 1893 } 1894 1895 $width = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0; 1896 $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0; 1897 1898 if ( $width && $height ) { 1899 $size_array = array( $width, $height ); 1900 } else { 1901 $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id ); 1902 if ( ! $size_array ) { 1903 return $image; 1904 } 1905 } 1906 1907 $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id ); 1908 1909 if ( $srcset ) { 1910 // Check if there is already a 'sizes' attribute. 1911 $sizes = strpos( $image, ' sizes=' ); 1912 1913 if ( ! $sizes ) { 1914 $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id ); 1915 } 1916 } 1917 1918 if ( $srcset && $sizes ) { 1919 // Format the 'srcset' and 'sizes' string and escape attributes. 1920 $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) ); 1921 1922 if ( is_string( $sizes ) ) { 1923 $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) ); 1924 } 1925 1926 // Add the srcset and sizes attributes to the image markup. 1927 return preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image ); 1928 } 1929 1930 return $image; 1931 } 1932 1933 /** 1934 * Determines whether to add the `loading` attribute to the specified tag in the specified context. 1935 * 1936 * @since 5.5.0 1937 * @since 5.7.0 Now returns `true` by default for `iframe` tags. 1938 * 1939 * @param string $tag_name The tag name. 1940 * @param string $context Additional context, like the current filter name 1941 * or the function name from where this was called. 1942 * @return bool Whether to add the attribute. 1943 */ 1944 function wp_lazy_loading_enabled( $tag_name, $context ) { 1945 /* 1946 * By default add to all 'img' and 'iframe' tags. 1947 * See https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading 1948 * See https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-loading 1949 */ 1950 $default = ( 'img' === $tag_name || 'iframe' === $tag_name ); 1951 1952 /** 1953 * Filters whether to add the `loading` attribute to the specified tag in the specified context. 1954 * 1955 * @since 5.5.0 1956 * 1957 * @param bool $default Default value. 1958 * @param string $tag_name The tag name. 1959 * @param string $context Additional context, like the current filter name 1960 * or the function name from where this was called. 1961 */ 1962 return (bool) apply_filters( 'wp_lazy_loading_enabled', $default, $tag_name, $context ); 1963 } 1964 1965 /** 1966 * Filters specific tags in post content and modifies their markup. 1967 * 1968 * Modifies HTML tags in post content to include new browser and HTML technologies 1969 * that may not have existed at the time of post creation. These modifications currently 1970 * include adding `srcset`, `sizes`, and `loading` attributes to `img` HTML tags, as well 1971 * as adding `loading` attributes to `iframe` HTML tags. 1972 * Future similar optimizations should be added/expected here. 1973 * 1974 * @since 5.5.0 1975 * @since 5.7.0 Now supports adding `loading` attributes to `iframe` tags. 1976 * 1977 * @see wp_img_tag_add_width_and_height_attr() 1978 * @see wp_img_tag_add_srcset_and_sizes_attr() 1979 * @see wp_img_tag_add_loading_optimization_attrs() 1980 * @see wp_iframe_tag_add_loading_attr() 1981 * 1982 * @param string $content The HTML content to be filtered. 1983 * @param string $context Optional. Additional context to pass to the filters. 1984 * Defaults to `current_filter()` when not set. 1985 * @return string Converted content with images modified. 1986 */ 1987 function wp_filter_content_tags( $content, $context = null ) { 1988 if ( null === $context ) { 1989 $context = current_filter(); 1990 } 1991 1992 $add_iframe_loading_attr = wp_lazy_loading_enabled( 'iframe', $context ); 1993 1994 if ( ! preg_match_all( '/<(img|iframe)\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ) { 1995 return $content; 1996 } 1997 1998 // List of the unique `img` tags found in $content. 1999 $images = array(); 2000 2001 // List of the unique `iframe` tags found in $content. 2002 $iframes = array(); 2003 2004 foreach ( $matches as $match ) { 2005 list( $tag, $tag_name ) = $match; 2006 2007 switch ( $tag_name ) { 2008 case 'img': 2009 if ( preg_match( '/wp-image-([0-9]+)/i', $tag, $class_id ) ) { 2010 $attachment_id = absint( $class_id[1] ); 2011 2012 if ( $attachment_id ) { 2013 /* 2014 * If exactly the same image tag is used more than once, overwrite it. 2015 * All identical tags will be replaced later with 'str_replace()'. 2016 */ 2017 $images[ $tag ] = $attachment_id; 2018 break; 2019 } 2020 } 2021 $images[ $tag ] = 0; 2022 break; 2023 case 'iframe': 2024 $iframes[ $tag ] = 0; 2025 break; 2026 } 2027 } 2028 2029 // Reduce the array to unique attachment IDs. 2030 $attachment_ids = array_unique( array_filter( array_values( $images ) ) ); 2031 2032 if ( count( $attachment_ids ) > 1 ) { 2033 /* 2034 * Warm the object cache with post and meta information for all found 2035 * images to avoid making individual database calls. 2036 */ 2037 _prime_post_caches( $attachment_ids, false, true ); 2038 } 2039 2040 // Iterate through the matches in order of occurrence as it is relevant for whether or not to lazy-load. 2041 foreach ( $matches as $match ) { 2042 // Filter an image match. 2043 if ( isset( $images[ $match[0] ] ) ) { 2044 $filtered_image = $match[0]; 2045 $attachment_id = $images[ $match[0] ]; 2046 2047 // Add 'width' and 'height' attributes if applicable. 2048 if ( $attachment_id > 0 && ! str_contains( $filtered_image, ' width=' ) && ! str_contains( $filtered_image, ' height=' ) ) { 2049 $filtered_image = wp_img_tag_add_width_and_height_attr( $filtered_image, $context, $attachment_id ); 2050 } 2051 2052 // Add 'srcset' and 'sizes' attributes if applicable. 2053 if ( $attachment_id > 0 && ! str_contains( $filtered_image, ' srcset=' ) ) { 2054 $filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id ); 2055 } 2056 2057 // Add loading optimization attributes if applicable. 2058 $filtered_image = wp_img_tag_add_loading_optimization_attrs( $filtered_image, $context ); 2059 2060 // Adds 'auto' to the sizes attribute if applicable. 2061 $filtered_image = wp_img_tag_add_auto_sizes( $filtered_image ); 2062 2063 /** 2064 * Filters an img tag within the content for a given context. 2065 * 2066 * @since 6.0.0 2067 * 2068 * @param string $filtered_image Full img tag with attributes that will replace the source img tag. 2069 * @param string $context Additional context, like the current filter name or the function name from where this was called. 2070 * @param int $attachment_id The image attachment ID. May be 0 in case the image is not an attachment. 2071 */ 2072 $filtered_image = apply_filters( 'wp_content_img_tag', $filtered_image, $context, $attachment_id ); 2073 2074 if ( $filtered_image !== $match[0] ) { 2075 $content = str_replace( $match[0], $filtered_image, $content ); 2076 } 2077 2078 /* 2079 * Unset image lookup to not run the same logic again unnecessarily if the same image tag is used more than 2080 * once in the same blob of content. 2081 */ 2082 unset( $images[ $match[0] ] ); 2083 } 2084 2085 // Filter an iframe match. 2086 if ( isset( $iframes[ $match[0] ] ) ) { 2087 $filtered_iframe = $match[0]; 2088 2089 // Add 'loading' attribute if applicable. 2090 if ( $add_iframe_loading_attr && ! str_contains( $filtered_iframe, ' loading=' ) ) { 2091 $filtered_iframe = wp_iframe_tag_add_loading_attr( $filtered_iframe, $context ); 2092 } 2093 2094 if ( $filtered_iframe !== $match[0] ) { 2095 $content = str_replace( $match[0], $filtered_iframe, $content ); 2096 } 2097 2098 /* 2099 * Unset iframe lookup to not run the same logic again unnecessarily if the same iframe tag is used more 2100 * than once in the same blob of content. 2101 */ 2102 unset( $iframes[ $match[0] ] ); 2103 } 2104 } 2105 2106 return $content; 2107 } 2108 2109 /** 2110 * Adds 'auto' to the sizes attribute to the image, if the image is lazy loaded and does not already include it. 2111 * 2112 * @since 6.7.0 2113 * 2114 * @param string $image The image tag markup being filtered. 2115 * @return string The filtered image tag markup. 2116 */ 2117 function wp_img_tag_add_auto_sizes( string $image ): string { 2118 /** 2119 * Filters whether auto-sizes for lazy loaded images is enabled. 2120 * 2121 * @since 6.7.1 2122 * 2123 * @param boolean $enabled Whether auto-sizes for lazy loaded images is enabled. 2124 */ 2125 if ( ! apply_filters( 'wp_img_tag_add_auto_sizes', true ) ) { 2126 return $image; 2127 } 2128 2129 $processor = new WP_HTML_Tag_Processor( $image ); 2130 2131 // Bail if there is no IMG tag. 2132 if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) ) { 2133 return $image; 2134 } 2135 2136 // Bail early if the image is not lazy-loaded. 2137 $loading = $processor->get_attribute( 'loading' ); 2138 if ( ! is_string( $loading ) || 'lazy' !== strtolower( trim( $loading, " \t\f\r\n" ) ) ) { 2139 return $image; 2140 } 2141 2142 /* 2143 * Bail early if the image doesn't have a width attribute. 2144 * Per WordPress Core itself, lazy-loaded images should always have a width attribute. 2145 * However, it is possible that lazy-loading could be added by a plugin, where we don't have that guarantee. 2146 * As such, it still makes sense to ensure presence of a width attribute here in order to use `sizes=auto`. 2147 */ 2148 $width = $processor->get_attribute( 'width' ); 2149 if ( ! is_string( $width ) || '' === $width ) { 2150 return $image; 2151 } 2152 2153 $sizes = $processor->get_attribute( 'sizes' ); 2154 2155 // Bail early if the image is not responsive. 2156 if ( ! is_string( $sizes ) ) { 2157 return $image; 2158 } 2159 2160 // Don't add 'auto' to the sizes attribute if it already exists. 2161 if ( wp_sizes_attribute_includes_valid_auto( $sizes ) ) { 2162 return $image; 2163 } 2164 2165 $processor->set_attribute( 'sizes', "auto, $sizes" ); 2166 return $processor->get_updated_html(); 2167 } 2168 2169 /** 2170 * Checks whether the given 'sizes' attribute includes the 'auto' keyword as the first item in the list. 2171 * 2172 * Per the HTML spec, if present it must be the first entry. 2173 * 2174 * @since 6.7.0 2175 * 2176 * @param string $sizes_attr The 'sizes' attribute value. 2177 * @return bool True if the 'auto' keyword is present, false otherwise. 2178 */ 2179 function wp_sizes_attribute_includes_valid_auto( string $sizes_attr ): bool { 2180 list( $first_size ) = explode( ',', $sizes_attr, 2 ); 2181 return 'auto' === strtolower( trim( $first_size, " \t\f\r\n" ) ); 2182 } 2183 2184 /** 2185 * Enqueues a CSS rule to fix potential visual issues with images using `sizes=auto`. 2186 * 2187 * This rule overrides the similar rule in the default user agent stylesheet, to avoid images that use e.g. 2188 * `width: auto` or `width: fit-content` to appear smaller. 2189 * 2190 * @since 6.9.0 2191 * 2192 * @see https://html.spec.whatwg.org/multipage/rendering.html#img-contain-size 2193 * @see https://core.trac.wordpress.org/ticket/62413 2194 * @see https://core.trac.wordpress.org/ticket/62731 2195 */ 2196 function wp_enqueue_img_auto_sizes_contain_css_fix(): void { 2197 // Back-compat for plugins that disable functionality by unhooking this action. 2198 $priority = has_action( 'wp_head', 'wp_print_auto_sizes_contain_css_fix' ); 2199 if ( false === $priority ) { 2200 return; 2201 } 2202 remove_action( 'wp_head', 'wp_print_auto_sizes_contain_css_fix', $priority ); 2203 2204 /** This filter is documented in wp-includes/media.php */ 2205 $add_auto_sizes = apply_filters( 'wp_img_tag_add_auto_sizes', true ); 2206 if ( ! $add_auto_sizes ) { 2207 return; 2208 } 2209 2210 $handle = 'wp-img-auto-sizes-contain'; 2211 wp_register_style( $handle, false ); 2212 wp_add_inline_style( $handle, 'img:is([sizes=auto i],[sizes^="auto," i]){contain-intrinsic-size:3000px 1500px}' ); 2213 2214 // Make sure inline style is printed first since it was previously printed at wp_head priority 1 and this preserves the CSS cascade. 2215 array_unshift( wp_styles()->queue, $handle ); 2216 } 2217 2218 /** 2219 * Adds optimization attributes to an `img` HTML tag. 2220 * 2221 * @since 6.3.0 2222 * 2223 * @param string $image The HTML `img` tag where the attribute should be added. 2224 * @param string $context Additional context to pass to the filters. 2225 * @return string Converted `img` tag with optimization attributes added. 2226 */ 2227 function wp_img_tag_add_loading_optimization_attrs( $image, $context ) { 2228 $src = preg_match( '/ src=["\']?([^"\']*)/i', $image, $matche_src ) ? $matche_src[1] : null; 2229 $width = preg_match( '/ width=["\']([0-9]+)["\']/', $image, $match_width ) ? (int) $match_width[1] : null; 2230 $height = preg_match( '/ height=["\']([0-9]+)["\']/', $image, $match_height ) ? (int) $match_height[1] : null; 2231 $loading_val = preg_match( '/ loading=["\']([A-Za-z]+)["\']/', $image, $match_loading ) ? $match_loading[1] : null; 2232 $fetchpriority_val = preg_match( '/ fetchpriority=["\']([A-Za-z]+)["\']/', $image, $match_fetchpriority ) ? $match_fetchpriority[1] : null; 2233 $decoding_val = preg_match( '/ decoding=["\']([A-Za-z]+)["\']/', $image, $match_decoding ) ? $match_decoding[1] : null; 2234 2235 /* 2236 * Get loading optimization attributes to use. 2237 * This must occur before the conditional check below so that even images 2238 * that are ineligible for being lazy-loaded are considered. 2239 */ 2240 $optimization_attrs = wp_get_loading_optimization_attributes( 2241 'img', 2242 array( 2243 'src' => $src, 2244 'width' => $width, 2245 'height' => $height, 2246 'loading' => $loading_val, 2247 'fetchpriority' => $fetchpriority_val, 2248 'decoding' => $decoding_val, 2249 ), 2250 $context 2251 ); 2252 2253 // Images should have source for the loading optimization attributes to be added. 2254 if ( ! str_contains( $image, ' src="' ) ) { 2255 return $image; 2256 } 2257 2258 if ( empty( $decoding_val ) ) { 2259 /** 2260 * Filters the `decoding` attribute value to add to an image. Default 'async'. 2261 * 2262 * Returning a falsey value will omit the attribute. 2263 * 2264 * @since 6.1.0 2265 * 2266 * @param string|false|null $value The `decoding` attribute value. Returning a falsey value 2267 * will result in the attribute being omitted for the image. 2268 * Otherwise, it may be: 'async', 'sync', or 'auto'. Defaults to false. 2269 * @param string $image The HTML `img` tag to be filtered. 2270 * @param string $context Additional context about how the function was called 2271 * or where the img tag is. 2272 */ 2273 $filtered_decoding_attr = apply_filters( 2274 'wp_img_tag_add_decoding_attr', 2275 $optimization_attrs['decoding'] ?? false, 2276 $image, 2277 $context 2278 ); 2279 2280 // Validate the values after filtering. 2281 if ( isset( $optimization_attrs['decoding'] ) && ! $filtered_decoding_attr ) { 2282 // Unset `decoding` attribute if `$filtered_decoding_attr` is set to `false`. 2283 unset( $optimization_attrs['decoding'] ); 2284 } elseif ( in_array( $filtered_decoding_attr, array( 'async', 'sync', 'auto' ), true ) ) { 2285 $optimization_attrs['decoding'] = $filtered_decoding_attr; 2286 } 2287 2288 if ( ! empty( $optimization_attrs['decoding'] ) ) { 2289 $image = str_replace( '<img', '<img decoding="' . esc_attr( $optimization_attrs['decoding'] ) . '"', $image ); 2290 } 2291 } 2292 2293 // Images should have dimension attributes for the 'loading' and 'fetchpriority' attributes to be added. 2294 if ( ! str_contains( $image, ' width="' ) || ! str_contains( $image, ' height="' ) ) { 2295 return $image; 2296 } 2297 2298 // Retained for backward compatibility. 2299 $loading_attrs_enabled = wp_lazy_loading_enabled( 'img', $context ); 2300 2301 if ( empty( $loading_val ) && $loading_attrs_enabled ) { 2302 /** 2303 * Filters the `loading` attribute value to add to an image. Default 'lazy'. 2304 * 2305 * Returning `false` or an empty string will not add the attribute. 2306 * Returning `true` will add the default value. 2307 * 2308 * @since 5.5.0 2309 * 2310 * @param string|bool $value The `loading` attribute value. Returning a falsey value will result in 2311 * the attribute being omitted for the image. 2312 * @param string $image The HTML `img` tag to be filtered. 2313 * @param string $context Additional context about how the function was called or where the img tag is. 2314 */ 2315 $filtered_loading_attr = apply_filters( 2316 'wp_img_tag_add_loading_attr', 2317 $optimization_attrs['loading'] ?? false, 2318 $image, 2319 $context 2320 ); 2321 2322 // Validate the values after filtering. 2323 if ( isset( $optimization_attrs['loading'] ) && ! $filtered_loading_attr ) { 2324 // Unset `loading` attributes if `$filtered_loading_attr` is set to `false`. 2325 unset( $optimization_attrs['loading'] ); 2326 } elseif ( in_array( $filtered_loading_attr, array( 'lazy', 'eager' ), true ) ) { 2327 /* 2328 * If the filter changed the loading attribute to "lazy" when a fetchpriority attribute 2329 * with value "high" is already present, trigger a warning since those two attribute 2330 * values should be mutually exclusive. 2331 * 2332 * The same warning is present in `wp_get_loading_optimization_attributes()`, and here it 2333 * is only intended for the specific scenario where the above filtered caused the problem. 2334 */ 2335 if ( isset( $optimization_attrs['fetchpriority'] ) && 'high' === $optimization_attrs['fetchpriority'] && 2336 ( $optimization_attrs['loading'] ?? false ) !== $filtered_loading_attr && 2337 'lazy' === $filtered_loading_attr 2338 ) { 2339 _doing_it_wrong( 2340 __FUNCTION__, 2341 __( 'An image should not be lazy-loaded and marked as high priority at the same time.' ), 2342 '6.3.0' 2343 ); 2344 } 2345 2346 // The filtered value will still be respected. 2347 $optimization_attrs['loading'] = $filtered_loading_attr; 2348 } 2349 2350 if ( ! empty( $optimization_attrs['loading'] ) ) { 2351 $image = str_replace( '<img', '<img loading="' . esc_attr( $optimization_attrs['loading'] ) . '"', $image ); 2352 } 2353 } 2354 2355 if ( empty( $fetchpriority_val ) && ! empty( $optimization_attrs['fetchpriority'] ) ) { 2356 $image = str_replace( '<img', '<img fetchpriority="' . esc_attr( $optimization_attrs['fetchpriority'] ) . '"', $image ); 2357 } 2358 2359 return $image; 2360 } 2361 2362 /** 2363 * Adds `width` and `height` attributes to an `img` HTML tag. 2364 * 2365 * @since 5.5.0 2366 * 2367 * @param string $image The HTML `img` tag where the attribute should be added. 2368 * @param string $context Additional context to pass to the filters. 2369 * @param int $attachment_id Image attachment ID. 2370 * @return string Converted 'img' element with 'width' and 'height' attributes added. 2371 */ 2372 function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) { 2373 $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : ''; 2374 list( $image_src ) = explode( '?', $image_src ); 2375 2376 // Return early if we couldn't get the image source. 2377 if ( ! $image_src ) { 2378 return $image; 2379 } 2380 2381 /** 2382 * Filters whether to add the missing `width` and `height` HTML attributes to the img tag. Default `true`. 2383 * 2384 * Returning anything else than `true` will not add the attributes. 2385 * 2386 * @since 5.5.0 2387 * 2388 * @param bool $value The filtered value, defaults to `true`. 2389 * @param string $image The HTML `img` tag where the attribute should be added. 2390 * @param string $context Additional context about how the function was called or where the img tag is. 2391 * @param int $attachment_id The image attachment ID. 2392 */ 2393 $add = apply_filters( 'wp_img_tag_add_width_and_height_attr', true, $image, $context, $attachment_id ); 2394 2395 if ( true === $add ) { 2396 $image_meta = wp_get_attachment_metadata( $attachment_id ); 2397 $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id ); 2398 2399 if ( $size_array && $size_array[0] && $size_array[1] ) { 2400 // If the width is enforced through style (e.g. in an inline image), calculate the dimension attributes. 2401 $style_width = preg_match( '/style="width:\s*(\d+)px;"/', $image, $match_width ) ? (int) $match_width[1] : 0; 2402 if ( $style_width ) { 2403 $size_array[1] = (int) round( $size_array[1] * $style_width / $size_array[0] ); 2404 $size_array[0] = $style_width; 2405 } 2406 2407 $hw = trim( image_hwstring( $size_array[0], $size_array[1] ) ); 2408 return str_replace( '<img', "<img {$hw}", $image ); 2409 } 2410 } 2411 2412 return $image; 2413 } 2414 2415 /** 2416 * Adds `srcset` and `sizes` attributes to an existing `img` HTML tag. 2417 * 2418 * @since 5.5.0 2419 * 2420 * @param string $image The HTML `img` tag where the attribute should be added. 2421 * @param string $context Additional context to pass to the filters. 2422 * @param int $attachment_id Image attachment ID. 2423 * @return string Converted 'img' element with 'loading' attribute added. 2424 */ 2425 function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) { 2426 /** 2427 * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`. 2428 * 2429 * Returning anything else than `true` will not add the attributes. 2430 * 2431 * @since 5.5.0 2432 * 2433 * @param bool $value The filtered value, defaults to `true`. 2434 * @param string $image The HTML `img` tag where the attribute should be added. 2435 * @param string $context Additional context about how the function was called or where the img tag is. 2436 * @param int $attachment_id The image attachment ID. 2437 */ 2438 $add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id ); 2439 2440 if ( true === $add ) { 2441 $image_meta = wp_get_attachment_metadata( $attachment_id ); 2442 return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ); 2443 } 2444 2445 return $image; 2446 } 2447 2448 /** 2449 * Adds `loading` attribute to an `iframe` HTML tag. 2450 * 2451 * @since 5.7.0 2452 * 2453 * @param string $iframe The HTML `iframe` tag where the attribute should be added. 2454 * @param string $context Additional context to pass to the filters. 2455 * @return string Converted `iframe` tag with `loading` attribute added. 2456 */ 2457 function wp_iframe_tag_add_loading_attr( $iframe, $context ) { 2458 /* 2459 * Get loading attribute value to use. This must occur before the conditional check below so that even iframes that 2460 * are ineligible for being lazy-loaded are considered. 2461 */ 2462 $optimization_attrs = wp_get_loading_optimization_attributes( 2463 'iframe', 2464 array( 2465 /* 2466 * The concrete values for width and height are not important here for now 2467 * since fetchpriority is not yet supported for iframes. 2468 * TODO: Use WP_HTML_Tag_Processor to extract actual values once support is 2469 * added. 2470 */ 2471 'width' => str_contains( $iframe, ' width="' ) ? 100 : null, 2472 'height' => str_contains( $iframe, ' height="' ) ? 100 : null, 2473 // This function is never called when a 'loading' attribute is already present. 2474 'loading' => null, 2475 ), 2476 $context 2477 ); 2478 2479 // Iframes should have source and dimension attributes for the `loading` attribute to be added. 2480 if ( ! str_contains( $iframe, ' src="' ) || ! str_contains( $iframe, ' width="' ) || ! str_contains( $iframe, ' height="' ) ) { 2481 return $iframe; 2482 } 2483 2484 $value = $optimization_attrs['loading'] ?? false; 2485 2486 /** 2487 * Filters the `loading` attribute value to add to an iframe. Default 'lazy'. 2488 * 2489 * Returning `false` or an empty string will not add the attribute. 2490 * Returning `true` will add the default value. 2491 * 2492 * @since 5.7.0 2493 * 2494 * @param string|bool $value The `loading` attribute value. Returning a falsey value will result in 2495 * the attribute being omitted for the iframe. 2496 * @param string $iframe The HTML `iframe` tag to be filtered. 2497 * @param string $context Additional context about how the function was called or where the iframe tag is. 2498 */ 2499 $value = apply_filters( 'wp_iframe_tag_add_loading_attr', $value, $iframe, $context ); 2500 2501 if ( $value ) { 2502 if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) { 2503 $value = 'lazy'; 2504 } 2505 2506 return str_replace( '<iframe', '<iframe loading="' . esc_attr( $value ) . '"', $iframe ); 2507 } 2508 2509 return $iframe; 2510 } 2511 2512 /** 2513 * Adds a 'wp-post-image' class to post thumbnails. Internal use only. 2514 * 2515 * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'} 2516 * action hooks to dynamically add/remove itself so as to only filter post thumbnails. 2517 * 2518 * @ignore 2519 * @since 2.9.0 2520 * 2521 * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name. 2522 * @return string[] Modified array of attributes including the new 'wp-post-image' class. 2523 */ 2524 function _wp_post_thumbnail_class_filter( $attr ) { 2525 $attr['class'] .= ' wp-post-image'; 2526 return $attr; 2527 } 2528 2529 /** 2530 * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes' 2531 * filter hook. Internal use only. 2532 * 2533 * @ignore 2534 * @since 2.9.0 2535 * 2536 * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name. 2537 */ 2538 function _wp_post_thumbnail_class_filter_add( $attr ) { 2539 add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' ); 2540 } 2541 2542 /** 2543 * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes' 2544 * filter hook. Internal use only. 2545 * 2546 * @ignore 2547 * @since 2.9.0 2548 * 2549 * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name. 2550 */ 2551 function _wp_post_thumbnail_class_filter_remove( $attr ) { 2552 remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' ); 2553 } 2554 2555 /** 2556 * Overrides the context used in {@see wp_get_attachment_image()}. Internal use only. 2557 * 2558 * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'} 2559 * action hooks to dynamically add/remove itself so as to only filter post thumbnails. 2560 * 2561 * @ignore 2562 * @since 6.3.0 2563 * @access private 2564 * 2565 * @param string $context The context for rendering an attachment image. 2566 * @return string Modified context set to 'the_post_thumbnail'. 2567 */ 2568 function _wp_post_thumbnail_context_filter( $context ) { 2569 return 'the_post_thumbnail'; 2570 } 2571 2572 /** 2573 * Adds the '_wp_post_thumbnail_context_filter' callback to the 'wp_get_attachment_image_context' 2574 * filter hook. Internal use only. 2575 * 2576 * @ignore 2577 * @since 6.3.0 2578 * @access private 2579 */ 2580 function _wp_post_thumbnail_context_filter_add() { 2581 add_filter( 'wp_get_attachment_image_context', '_wp_post_thumbnail_context_filter' ); 2582 } 2583 2584 /** 2585 * Removes the '_wp_post_thumbnail_context_filter' callback from the 'wp_get_attachment_image_context' 2586 * filter hook. Internal use only. 2587 * 2588 * @ignore 2589 * @since 6.3.0 2590 * @access private 2591 */ 2592 function _wp_post_thumbnail_context_filter_remove() { 2593 remove_filter( 'wp_get_attachment_image_context', '_wp_post_thumbnail_context_filter' ); 2594 } 2595 2596 add_shortcode( 'wp_caption', 'img_caption_shortcode' ); 2597 add_shortcode( 'caption', 'img_caption_shortcode' ); 2598 2599 /** 2600 * Builds the Caption shortcode output. 2601 * 2602 * Allows a plugin to replace the content that would otherwise be returned. The 2603 * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr 2604 * parameter and the content parameter values. 2605 * 2606 * The supported attributes for the shortcode are 'id', 'caption_id', 'align', 2607 * 'width', 'caption', and 'class'. 2608 * 2609 * @since 2.6.0 2610 * @since 3.9.0 The `class` attribute was added. 2611 * @since 5.1.0 The `caption_id` attribute was added. 2612 * @since 5.9.0 The `$content` parameter default value changed from `null` to `''`. 2613 * 2614 * @param array $attr { 2615 * Attributes of the caption shortcode. 2616 * 2617 * @type string $id ID of the image and caption container element, i.e. `<figure>` or `<div>`. 2618 * @type string $caption_id ID of the caption element, i.e. `<figcaption>` or `<p>`. 2619 * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft', 2620 * 'aligncenter', alignright', 'alignnone'. 2621 * @type int $width The width of the caption, in pixels. 2622 * @type string $caption The caption text. 2623 * @type string $class Additional class name(s) added to the caption container. 2624 * } 2625 * @param string $content Optional. Shortcode content. Default empty string. 2626 * @return string HTML content to display the caption. 2627 */ 2628 function img_caption_shortcode( $attr, $content = '' ) { 2629 // New-style shortcode with the caption inside the shortcode with the link and image tags. 2630 if ( ! isset( $attr['caption'] ) ) { 2631 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) { 2632 $content = $matches[1]; 2633 $attr['caption'] = trim( $matches[2] ); 2634 } 2635 } elseif ( str_contains( $attr['caption'], '<' ) ) { 2636 $attr['caption'] = wp_kses( $attr['caption'], 'post' ); 2637 } 2638 2639 /** 2640 * Filters the default caption shortcode output. 2641 * 2642 * If the filtered output isn't empty, it will be used instead of generating 2643 * the default caption template. 2644 * 2645 * @since 2.6.0 2646 * 2647 * @see img_caption_shortcode() 2648 * 2649 * @param string $output The caption output. Default empty. 2650 * @param array $attr Attributes of the caption shortcode. 2651 * @param string $content The image element, possibly wrapped in a hyperlink. 2652 */ 2653 $output = apply_filters( 'img_caption_shortcode', '', $attr, $content ); 2654 2655 if ( ! empty( $output ) ) { 2656 return $output; 2657 } 2658 2659 /** 2660 * @var array{ 2661 * id: string, 2662 * caption_id: string, 2663 * align: string, 2664 * width: string, 2665 * caption: string, 2666 * class: string, 2667 * } $atts 2668 */ 2669 $atts = shortcode_atts( 2670 array( 2671 'id' => '', 2672 'caption_id' => '', 2673 'align' => 'alignnone', 2674 'width' => '', 2675 'caption' => '', 2676 'class' => '', 2677 ), 2678 $attr, 2679 'caption' 2680 ); 2681 2682 $atts['width'] = (int) $atts['width']; 2683 2684 if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) { 2685 return $content; 2686 } 2687 2688 $id = ''; 2689 $caption_id = ''; 2690 $describedby = ''; 2691 $unique_id_value = ''; 2692 $caption_id_value = ''; 2693 2694 if ( $atts['id'] ) { 2695 $atts['id'] = sanitize_html_class( $atts['id'] ); 2696 $unique_id_value = (string) preg_replace( '/-1$/', '', wp_unique_prefixed_id( $atts['id'] . '-' ) ); 2697 $id = 'id="' . esc_attr( $unique_id_value ) . '" '; 2698 } 2699 2700 if ( $atts['caption_id'] ) { 2701 // User explicitly provided a caption_id - make it unique. 2702 $atts['caption_id'] = sanitize_html_class( $atts['caption_id'] ); 2703 $caption_id_value = preg_replace( '/-1$/', '', wp_unique_prefixed_id( $atts['caption_id'] . '-' ) ); 2704 } elseif ( $unique_id_value ) { 2705 // Derive from the already-unique figure ID - guaranteed unique, no need for second call. 2706 $caption_id_value = 'caption-' . str_replace( '_', '-', $unique_id_value ); 2707 } 2708 2709 if ( $caption_id_value ) { 2710 $caption_id = 'id="' . esc_attr( $caption_id_value ) . '" '; 2711 $describedby = 'aria-describedby="' . esc_attr( $caption_id_value ) . '" '; 2712 } 2713 2714 $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] ); 2715 2716 $html5 = current_theme_supports( 'html5', 'caption' ); 2717 // HTML5 captions never added the extra 10px to the image width. 2718 $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] ); 2719 2720 /** 2721 * Filters the width of an image's caption. 2722 * 2723 * By default, the caption is 10 pixels greater than the width of the image, 2724 * to prevent post content from running up against a floated image. 2725 * 2726 * @since 3.7.0 2727 * 2728 * @see img_caption_shortcode() 2729 * 2730 * @param int $width Width of the caption in pixels. To remove this inline style, 2731 * return zero. 2732 * @param array $atts Attributes of the caption shortcode. 2733 * @param string $content The image element, possibly wrapped in a hyperlink. 2734 */ 2735 $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content ); 2736 2737 $style = ''; 2738 2739 if ( $caption_width ) { 2740 $style = 'style="width: ' . (int) $caption_width . 'px" '; 2741 } 2742 2743 if ( $html5 ) { 2744 $html = sprintf( 2745 '<figure %s%s%sclass="%s">%s%s</figure>', 2746 $id, 2747 $describedby, 2748 $style, 2749 esc_attr( $class ), 2750 do_shortcode( $content ), 2751 sprintf( 2752 '<figcaption %sclass="wp-caption-text">%s</figcaption>', 2753 $caption_id, 2754 $atts['caption'] 2755 ) 2756 ); 2757 } else { 2758 $html = sprintf( 2759 '<div %s%sclass="%s">%s%s</div>', 2760 $id, 2761 $style, 2762 esc_attr( $class ), 2763 str_replace( '<img ', '<img ' . $describedby, do_shortcode( $content ) ), 2764 sprintf( 2765 '<p %sclass="wp-caption-text">%s</p>', 2766 $caption_id, 2767 $atts['caption'] 2768 ) 2769 ); 2770 } 2771 2772 return $html; 2773 } 2774 2775 add_shortcode( 'gallery', 'gallery_shortcode' ); 2776 2777 /** 2778 * Builds the Gallery shortcode output. 2779 * 2780 * This implements the functionality of the Gallery Shortcode for displaying 2781 * WordPress images on a post. 2782 * 2783 * @since 2.5.0 2784 * @since 2.8.0 Added the `$attr` parameter to set the shortcode output. New attributes included 2785 * such as `size`, `itemtag`, `icontag`, `captiontag`, and columns. Changed markup from 2786 * `div` tags to `dl`, `dt` and `dd` tags. Support more than one gallery on the 2787 * same page. 2788 * @since 2.9.0 Added support for `include` and `exclude` to shortcode. 2789 * @since 3.5.0 Use get_post() instead of global `$post`. Handle mapping of `ids` to `include` 2790 * and `orderby`. 2791 * @since 3.6.0 Added validation for tags used in gallery shortcode. Add orientation information to items. 2792 * @since 3.7.0 Introduced the `link` attribute. 2793 * @since 3.9.0 `html5` gallery support, accepting 'itemtag', 'icontag', and 'captiontag' attributes. 2794 * @since 4.0.0 Removed use of `extract()`. 2795 * @since 4.1.0 Added attribute to `wp_get_attachment_link()` to output `aria-describedby`. 2796 * @since 4.2.0 Passed the shortcode instance ID to `post_gallery` and `post_playlist` filters. 2797 * @since 4.6.0 Standardized filter docs to match documentation standards for PHP. 2798 * @since 5.1.0 Code cleanup for WPCS 1.0.0 coding standards. 2799 * @since 5.3.0 Saved progress of intermediate image creation after upload. 2800 * @since 5.5.0 Ensured that galleries can be output as a list of links in feeds. 2801 * @since 5.6.0 Replaced order-style PHP type conversion functions with typecasts. Fix logic for 2802 * an array of image dimensions. 2803 * 2804 * @param array $attr { 2805 * Attributes of the gallery shortcode. 2806 * 2807 * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'. 2808 * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'. 2809 * Accepts any valid SQL ORDERBY statement. 2810 * @type int $id Post ID. 2811 * @type string $itemtag HTML tag to use for each image in the gallery. 2812 * Default 'dl', or 'figure' when the theme registers HTML5 gallery support. 2813 * @type string $icontag HTML tag to use for each image's icon. 2814 * Default 'dt', or 'div' when the theme registers HTML5 gallery support. 2815 * @type string $captiontag HTML tag to use for each image's caption. 2816 * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support. 2817 * @type int $columns Number of columns of images to display. Default 3. 2818 * @type string|int[] $size Size of the images to display. Accepts any registered image size name, or an array 2819 * of width and height values in pixels (in that order). Default 'thumbnail'. 2820 * @type string $ids A comma-separated list of IDs of attachments to display. Default empty. 2821 * @type string $include A comma-separated list of IDs of attachments to include. Default empty. 2822 * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty. 2823 * @type string $link What to link each image to. Default empty (links to the attachment page). 2824 * Accepts 'file', 'none'. 2825 * } 2826 * @return string HTML content to display gallery. 2827 */ 2828 function gallery_shortcode( $attr ) { 2829 $post = get_post(); 2830 2831 static $instance = 0; 2832 ++$instance; 2833 2834 if ( ! empty( $attr['ids'] ) ) { 2835 // 'ids' is explicitly ordered, unless you specify otherwise. 2836 if ( empty( $attr['orderby'] ) ) { 2837 $attr['orderby'] = 'post__in'; 2838 } 2839 $attr['include'] = $attr['ids']; 2840 } 2841 2842 /** 2843 * Filters the default gallery shortcode output. 2844 * 2845 * If the filtered output isn't empty, it will be used instead of generating 2846 * the default gallery template. 2847 * 2848 * @since 2.5.0 2849 * @since 4.2.0 The `$instance` parameter was added. 2850 * 2851 * @see gallery_shortcode() 2852 * 2853 * @param string $output The gallery output. Default empty. 2854 * @param array $attr Attributes of the gallery shortcode. 2855 * @param int $instance Unique numeric ID of this gallery shortcode instance. 2856 */ 2857 $output = apply_filters( 'post_gallery', '', $attr, $instance ); 2858 2859 if ( ! empty( $output ) ) { 2860 return $output; 2861 } 2862 2863 $html5 = current_theme_supports( 'html5', 'gallery' ); 2864 $atts = shortcode_atts( 2865 array( 2866 'order' => 'ASC', 2867 'orderby' => 'menu_order ID', 2868 'id' => $post ? $post->ID : 0, 2869 'itemtag' => $html5 ? 'figure' : 'dl', 2870 'icontag' => $html5 ? 'div' : 'dt', 2871 'captiontag' => $html5 ? 'figcaption' : 'dd', 2872 'columns' => 3, 2873 'size' => 'thumbnail', 2874 'include' => '', 2875 'exclude' => '', 2876 'link' => '', 2877 ), 2878 $attr, 2879 'gallery' 2880 ); 2881 2882 $id = (int) $atts['id']; 2883 2884 if ( ! empty( $atts['include'] ) ) { 2885 $_attachments = get_posts( 2886 array( 2887 'include' => $atts['include'], 2888 'post_status' => 'inherit', 2889 'post_type' => 'attachment', 2890 'post_mime_type' => 'image', 2891 'order' => $atts['order'], 2892 'orderby' => $atts['orderby'], 2893 ) 2894 ); 2895 2896 $attachments = array(); 2897 foreach ( $_attachments as $key => $val ) { 2898 $attachments[ $val->ID ] = $_attachments[ $key ]; 2899 } 2900 } elseif ( ! empty( $atts['exclude'] ) ) { 2901 $post_parent_id = $id; 2902 $attachments = get_children( 2903 array( 2904 'post_parent' => $id, 2905 'exclude' => $atts['exclude'], 2906 'post_status' => 'inherit', 2907 'post_type' => 'attachment', 2908 'post_mime_type' => 'image', 2909 'order' => $atts['order'], 2910 'orderby' => $atts['orderby'], 2911 ) 2912 ); 2913 } else { 2914 $post_parent_id = $id; 2915 $attachments = get_children( 2916 array( 2917 'post_parent' => $id, 2918 'post_status' => 'inherit', 2919 'post_type' => 'attachment', 2920 'post_mime_type' => 'image', 2921 'order' => $atts['order'], 2922 'orderby' => $atts['orderby'], 2923 ) 2924 ); 2925 } 2926 2927 if ( ! empty( $post_parent_id ) ) { 2928 $post_parent = get_post( $post_parent_id ); 2929 2930 // Terminate the shortcode execution if the user cannot read the post or it is password-protected. 2931 if ( ! is_post_publicly_viewable( $post_parent->ID ) && ! current_user_can( 'read_post', $post_parent->ID ) 2932 || post_password_required( $post_parent ) 2933 ) { 2934 return ''; 2935 } 2936 } 2937 2938 if ( empty( $attachments ) ) { 2939 return ''; 2940 } 2941 2942 if ( is_feed() ) { 2943 $output = "\n"; 2944 foreach ( $attachments as $att_id => $attachment ) { 2945 if ( ! empty( $atts['link'] ) ) { 2946 if ( 'none' === $atts['link'] ) { 2947 $output .= wp_get_attachment_image( $att_id, $atts['size'], false, $attr ); 2948 } else { 2949 $output .= wp_get_attachment_link( $att_id, $atts['size'], false ); 2950 } 2951 } else { 2952 $output .= wp_get_attachment_link( $att_id, $atts['size'], true ); 2953 } 2954 $output .= "\n"; 2955 } 2956 return $output; 2957 } 2958 2959 $itemtag = tag_escape( $atts['itemtag'] ); 2960 $captiontag = tag_escape( $atts['captiontag'] ); 2961 $icontag = tag_escape( $atts['icontag'] ); 2962 $valid_tags = wp_kses_allowed_html( 'post' ); 2963 if ( ! isset( $valid_tags[ $itemtag ] ) ) { 2964 $itemtag = 'dl'; 2965 } 2966 if ( ! isset( $valid_tags[ $captiontag ] ) ) { 2967 $captiontag = 'dd'; 2968 } 2969 if ( ! isset( $valid_tags[ $icontag ] ) ) { 2970 $icontag = 'dt'; 2971 } 2972 2973 $columns = (int) $atts['columns']; 2974 $itemwidth = $columns > 0 ? floor( 100 / $columns ) : 100; 2975 $float = is_rtl() ? 'right' : 'left'; 2976 2977 $selector = "gallery-{$instance}"; 2978 2979 $gallery_style = ''; 2980 2981 /** 2982 * Filters whether to print default gallery styles. 2983 * 2984 * @since 3.1.0 2985 * @since 3.9.0 Set the default to false when the theme supports HTML5 galleries. 2986 * 2987 * @param bool $print Whether to print default gallery styles. 2988 * Defaults to false if the theme supports HTML5 galleries. 2989 * Otherwise, defaults to true. 2990 */ 2991 if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) { 2992 $gallery_style = " 2993 <style> 2994 #{$selector} { 2995 margin: auto; 2996 } 2997 #{$selector} .gallery-item { 2998 float: {$float}; 2999 margin-top: 10px; 3000 text-align: center; 3001 width: {$itemwidth}%; 3002 } 3003 #{$selector} img { 3004 border: 2px solid #cfcfcf; 3005 } 3006 #{$selector} .gallery-caption { 3007 margin-left: 0; 3008 } 3009 /* see gallery_shortcode() in wp-includes/media.php */ 3010 </style>\n\t\t"; 3011 } 3012 3013 $size_class = sanitize_html_class( is_array( $atts['size'] ) ? implode( 'x', $atts['size'] ) : $atts['size'] ); 3014 $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>"; 3015 3016 /** 3017 * Filters the gallery shortcode's default CSS styles and opening HTML div container. 3018 * 3019 * To remove the CSS entirely, use the `use_default_gallery_style` filter instead: 3020 * 3021 * add_filter( 'use_default_gallery_style', '__return_false' ); 3022 * 3023 * @since 2.5.0 3024 * @since 3.1.0 Added classes for number of columns and size to opening div. 3025 * @since 5.3.0 Removed the `type` attribute for `style` tags when the theme 3026 * supports HTML5 style, and changed the quotes from single to 3027 * double for other themes. 3028 * @since 7.0.0 Removed the `type` attribute for any theme. 3029 * 3030 * @param string $gallery_style Default CSS styles and opening HTML div container 3031 * for the gallery shortcode output. 3032 */ 3033 $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div ); 3034 3035 $i = 0; 3036 3037 foreach ( $attachments as $id => $attachment ) { 3038 3039 $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : ''; 3040 3041 if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) { 3042 $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr ); 3043 } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) { 3044 $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr ); 3045 } else { 3046 $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr ); 3047 } 3048 3049 $image_meta = wp_get_attachment_metadata( $id ); 3050 3051 $orientation = ''; 3052 3053 if ( isset( $image_meta['height'], $image_meta['width'] ) ) { 3054 $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape'; 3055 } 3056 3057 $output .= "<{$itemtag} class='gallery-item'>"; 3058 $output .= " 3059 <{$icontag} class='gallery-icon {$orientation}'> 3060 $image_output 3061 </{$icontag}>"; 3062 3063 if ( $captiontag && trim( $attachment->post_excerpt ) ) { 3064 $output .= " 3065 <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'> 3066 " . wptexturize( $attachment->post_excerpt ) . " 3067 </{$captiontag}>"; 3068 } 3069 3070 $output .= "</{$itemtag}>"; 3071 3072 if ( ! $html5 && $columns > 0 && 0 === ++$i % $columns ) { 3073 $output .= '<br style="clear: both" />'; 3074 } 3075 } 3076 3077 if ( ! $html5 && $columns > 0 && 0 !== $i % $columns ) { 3078 $output .= " 3079 <br style='clear: both' />"; 3080 } 3081 3082 $output .= " 3083 </div>\n"; 3084 3085 return $output; 3086 } 3087 3088 /** 3089 * Outputs the templates used by playlists. 3090 * 3091 * @since 3.9.0 3092 */ 3093 function wp_underscore_playlist_templates() { 3094 ?> 3095 <script type="text/html" id="tmpl-wp-playlist-current-item"> 3096 <# if ( data.thumb && data.thumb.src ) { #> 3097 <img src="{{ data.thumb.src }}" alt="" /> 3098 <# } #> 3099 <div class="wp-playlist-caption"> 3100 <span class="wp-playlist-item-meta wp-playlist-item-title"> 3101 <# if ( data.meta.album || data.meta.artist ) { #> 3102 <?php 3103 /* translators: %s: Playlist item title. */ 3104 printf( _x( '“%s”', 'playlist item title' ), '{{ data.title }}' ); 3105 ?> 3106 <# } else { #> 3107 {{ data.title }} 3108 <# } #> 3109 </span> 3110 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #> 3111 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #> 3112 </div> 3113 </script> 3114 <script type="text/html" id="tmpl-wp-playlist-item"> 3115 <div class="wp-playlist-item"> 3116 <a class="wp-playlist-caption" href="{{ data.src }}"> 3117 {{ data.index ? ( data.index + '. ' ) : '' }} 3118 <# if ( data.caption ) { #> 3119 {{ data.caption }} 3120 <# } else { #> 3121 <# if ( data.artists && data.meta.artist ) { #> 3122 <span class="wp-playlist-item-title"> 3123 <?php 3124 /* translators: %s: Playlist item title. */ 3125 printf( _x( '“%s”', 'playlist item title' ), '{{{ data.title }}}' ); 3126 ?> 3127 </span> 3128 <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span> 3129 <# } else { #> 3130 <span class="wp-playlist-item-title">{{{ data.title }}}</span> 3131 <# } #> 3132 <# } #> 3133 </a> 3134 <# if ( data.meta.length_formatted ) { #> 3135 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div> 3136 <# } #> 3137 </div> 3138 </script> 3139 <?php 3140 } 3141 3142 /** 3143 * Outputs and enqueues default scripts and styles for playlists. 3144 * 3145 * @since 3.9.0 3146 * 3147 * @param string $type Type of playlist. Accepts 'audio' or 'video'. 3148 */ 3149 function wp_playlist_scripts( $type ) { 3150 wp_enqueue_style( 'wp-mediaelement' ); 3151 wp_enqueue_script( 'wp-playlist' ); 3152 add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 ); 3153 add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 ); 3154 } 3155 3156 /** 3157 * Builds the Playlist shortcode output. 3158 * 3159 * This implements the functionality of the playlist shortcode for displaying 3160 * a collection of WordPress audio or video files in a post. 3161 * 3162 * @since 3.9.0 3163 * 3164 * @global int $content_width 3165 * 3166 * @param array $attr { 3167 * Array of default playlist attributes. 3168 * 3169 * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'. 3170 * @type string $order Designates ascending or descending order of items in the playlist. 3171 * Accepts 'ASC', 'DESC'. Default 'ASC'. 3172 * @type string $orderby Any column, or columns, to sort the playlist. If $ids are 3173 * passed, this defaults to the order of the $ids array ('post__in'). 3174 * Otherwise default is 'menu_order ID'. 3175 * @type int $id If an explicit $ids array is not present, this parameter 3176 * will determine which attachments are used for the playlist. 3177 * Default is the current post ID. 3178 * @type array $ids Create a playlist out of these explicit attachment IDs. If empty, 3179 * a playlist will be created from all $type attachments of $id. 3180 * Default empty. 3181 * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty. 3182 * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'. 3183 * @type bool $tracklist Whether to show or hide the playlist. Default true. 3184 * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true. 3185 * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post 3186 * thumbnail). Default true. 3187 * @type bool $artists Whether to show or hide artist name in the playlist. Default true. 3188 * } 3189 * 3190 * @return string Playlist output. Empty string if the passed type is unsupported. 3191 */ 3192 function wp_playlist_shortcode( $attr ) { 3193 global $content_width; 3194 $post = get_post(); 3195 3196 static $instance = 0; 3197 ++$instance; 3198 3199 static $is_loaded = false; 3200 3201 if ( ! empty( $attr['ids'] ) ) { 3202 // 'ids' is explicitly ordered, unless you specify otherwise. 3203 if ( empty( $attr['orderby'] ) ) { 3204 $attr['orderby'] = 'post__in'; 3205 } 3206 $attr['include'] = $attr['ids']; 3207 } 3208 3209 /** 3210 * Filters the playlist output. 3211 * 3212 * Returning a non-empty value from the filter will short-circuit generation 3213 * of the default playlist output, returning the passed value instead. 3214 * 3215 * @since 3.9.0 3216 * @since 4.2.0 The `$instance` parameter was added. 3217 * 3218 * @param string $output Playlist output. Default empty. 3219 * @param array $attr An array of shortcode attributes. 3220 * @param int $instance Unique numeric ID of this playlist shortcode instance. 3221 */ 3222 $output = apply_filters( 'post_playlist', '', $attr, $instance ); 3223 3224 if ( ! empty( $output ) ) { 3225 return $output; 3226 } 3227 3228 $atts = shortcode_atts( 3229 array( 3230 'type' => 'audio', 3231 'order' => 'ASC', 3232 'orderby' => 'menu_order ID', 3233 'id' => $post ? $post->ID : 0, 3234 'include' => '', 3235 'exclude' => '', 3236 'style' => 'light', 3237 'tracklist' => true, 3238 'tracknumbers' => true, 3239 'images' => true, 3240 'artists' => true, 3241 ), 3242 $attr, 3243 'playlist' 3244 ); 3245 3246 $id = (int) $atts['id']; 3247 3248 if ( 'audio' !== $atts['type'] ) { 3249 $atts['type'] = 'video'; 3250 } 3251 3252 $args = array( 3253 'post_status' => 'inherit', 3254 'post_type' => 'attachment', 3255 'post_mime_type' => $atts['type'], 3256 'order' => $atts['order'], 3257 'orderby' => $atts['orderby'], 3258 ); 3259 3260 if ( ! empty( $atts['include'] ) ) { 3261 $args['include'] = $atts['include']; 3262 $_attachments = get_posts( $args ); 3263 3264 $attachments = array(); 3265 foreach ( $_attachments as $key => $val ) { 3266 $attachments[ $val->ID ] = $_attachments[ $key ]; 3267 } 3268 } elseif ( ! empty( $atts['exclude'] ) ) { 3269 $args['post_parent'] = $id; 3270 $args['exclude'] = $atts['exclude']; 3271 $attachments = get_children( $args ); 3272 } else { 3273 $args['post_parent'] = $id; 3274 $attachments = get_children( $args ); 3275 } 3276 3277 if ( ! empty( $args['post_parent'] ) ) { 3278 $post_parent = get_post( $id ); 3279 3280 // Terminate the shortcode execution if the user cannot read the post or it is password-protected. 3281 if ( ! current_user_can( 'read_post', $post_parent->ID ) || post_password_required( $post_parent ) ) { 3282 return ''; 3283 } 3284 } 3285 3286 if ( empty( $attachments ) ) { 3287 return ''; 3288 } 3289 3290 if ( is_feed() ) { 3291 $output = "\n"; 3292 foreach ( $attachments as $att_id => $attachment ) { 3293 $output .= wp_get_attachment_link( $att_id ) . "\n"; 3294 } 3295 return $output; 3296 } 3297 3298 $outer = 22; // Default padding and border of wrapper. 3299 3300 $default_width = 640; 3301 $default_height = 360; 3302 3303 $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer ); 3304 $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width ); 3305 3306 $data = array( 3307 'type' => $atts['type'], 3308 // Don't pass strings to JSON, will be truthy in JS. 3309 'tracklist' => wp_validate_boolean( $atts['tracklist'] ), 3310 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ), 3311 'images' => wp_validate_boolean( $atts['images'] ), 3312 'artists' => wp_validate_boolean( $atts['artists'] ), 3313 ); 3314 3315 $tracks = array(); 3316 foreach ( $attachments as $attachment ) { 3317 $url = wp_get_attachment_url( $attachment->ID ); 3318 $ftype = wp_check_filetype( $url, wp_get_mime_types() ); 3319 $track = array( 3320 'src' => $url, 3321 'type' => $ftype['type'], 3322 'title' => $attachment->post_title, 3323 'caption' => $attachment->post_excerpt, 3324 'description' => $attachment->post_content, 3325 ); 3326 3327 $track['meta'] = array(); 3328 $meta = wp_get_attachment_metadata( $attachment->ID ); 3329 if ( ! empty( $meta ) ) { 3330 3331 foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) { 3332 if ( ! empty( $meta[ $key ] ) ) { 3333 $track['meta'][ $key ] = $meta[ $key ]; 3334 } 3335 } 3336 3337 if ( 'video' === $atts['type'] ) { 3338 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) { 3339 $width = $meta['width']; 3340 $height = $meta['height']; 3341 $theme_height = round( ( $height * $theme_width ) / $width ); 3342 } else { 3343 $width = $default_width; 3344 $height = $default_height; 3345 } 3346 3347 $track['dimensions'] = array( 3348 'original' => compact( 'width', 'height' ), 3349 'resized' => array( 3350 'width' => $theme_width, 3351 'height' => $theme_height, 3352 ), 3353 ); 3354 } 3355 } 3356 3357 if ( $atts['images'] ) { 3358 $thumb_id = get_post_thumbnail_id( $attachment->ID ); 3359 if ( ! empty( $thumb_id ) ) { 3360 $image_src_full = wp_get_attachment_image_src( $thumb_id, 'full' ); 3361 if ( is_array( $image_src_full ) ) { 3362 $track['image'] = array( 3363 'src' => $image_src_full[0], 3364 'width' => $image_src_full[1], 3365 'height' => $image_src_full[2], 3366 ); 3367 } 3368 3369 $image_src_thumb = wp_get_attachment_image_src( $thumb_id, 'thumbnail' ); 3370 if ( is_array( $image_src_thumb ) ) { 3371 $track['thumb'] = array( 3372 'src' => $image_src_thumb[0], 3373 'width' => $image_src_thumb[1], 3374 'height' => $image_src_thumb[2], 3375 ); 3376 } 3377 } else { 3378 $src = wp_mime_type_icon( $attachment->ID, '.svg' ); 3379 $width = 48; 3380 $height = 64; 3381 $track['image'] = compact( 'src', 'width', 'height' ); 3382 $track['thumb'] = compact( 'src', 'width', 'height' ); 3383 } 3384 } 3385 3386 $tracks[] = $track; 3387 } 3388 $data['tracks'] = $tracks; 3389 3390 $safe_type = esc_attr( $atts['type'] ); 3391 $safe_style = esc_attr( $atts['style'] ); 3392 3393 ob_start(); 3394 3395 if ( ! $is_loaded ) { 3396 /** 3397 * Prints and enqueues playlist scripts, styles, and JavaScript templates. 3398 * 3399 * @since 3.9.0 3400 * 3401 * @param string $type Type of playlist. Possible values are 'audio' or 'video'. 3402 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'. 3403 */ 3404 do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] ); 3405 $is_loaded = true; 3406 } 3407 ?> 3408 <div class="wp-playlist wp-<?php echo $safe_type; ?>-playlist wp-playlist-<?php echo $safe_style; ?>"> 3409 <?php if ( 'audio' === $atts['type'] ) : ?> 3410 <div class="wp-playlist-current-item"></div> 3411 <?php endif; ?> 3412 <<?php echo $safe_type; ?> controls="controls" preload="none" width="<?php echo (int) $theme_width; ?>" 3413 <?php 3414 if ( 'video' === $safe_type ) { 3415 echo ' height="', (int) $theme_height, '"'; 3416 } 3417 ?> 3418 ></<?php echo $safe_type; ?>> 3419 <div class="wp-playlist-next"></div> 3420 <div class="wp-playlist-prev"></div> 3421 <noscript> 3422 <ol> 3423 <?php 3424 foreach ( $attachments as $att_id => $attachment ) { 3425 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) ); 3426 } 3427 ?> 3428 </ol> 3429 </noscript> 3430 <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ); ?></script> 3431 </div> 3432 <?php 3433 return ob_get_clean(); 3434 } 3435 add_shortcode( 'playlist', 'wp_playlist_shortcode' ); 3436 3437 /** 3438 * Provides a No-JS Flash fallback as a last resort for audio / video. 3439 * 3440 * @since 3.6.0 3441 * 3442 * @param string $url The media element URL. 3443 * @return string Fallback HTML. 3444 */ 3445 function wp_mediaelement_fallback( $url ) { 3446 /** 3447 * Filters the MediaElement fallback output for no-JS. 3448 * 3449 * @since 3.6.0 3450 * 3451 * @param string $output Fallback output for no-JS. 3452 * @param string $url Media file URL. 3453 */ 3454 return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url ); 3455 } 3456 3457 /** 3458 * Returns a filtered list of supported audio formats. 3459 * 3460 * @since 3.6.0 3461 * 3462 * @return string[] Supported audio formats. 3463 */ 3464 function wp_get_audio_extensions() { 3465 /** 3466 * Filters the list of supported audio formats. 3467 * 3468 * @since 3.6.0 3469 * 3470 * @param string[] $extensions An array of supported audio formats. Defaults are 3471 * 'mp3', 'ogg', 'flac', 'm4a', 'wav'. 3472 */ 3473 return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ) ); 3474 } 3475 3476 /** 3477 * Returns useful keys to use to lookup data from an attachment's stored metadata. 3478 * 3479 * @since 3.9.0 3480 * 3481 * @param WP_Post $attachment The current attachment, provided for context. 3482 * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'. 3483 * @return string[] Key/value pairs of field keys to labels. 3484 */ 3485 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) { 3486 $fields = array( 3487 'artist' => __( 'Artist' ), 3488 'album' => __( 'Album' ), 3489 ); 3490 3491 if ( 'display' === $context ) { 3492 $fields['genre'] = __( 'Genre' ); 3493 $fields['year'] = __( 'Year' ); 3494 $fields['length_formatted'] = _x( 'Length', 'video or audio' ); 3495 } elseif ( 'js' === $context ) { 3496 $fields['bitrate'] = __( 'Bitrate' ); 3497 $fields['bitrate_mode'] = __( 'Bitrate Mode' ); 3498 } 3499 3500 /** 3501 * Filters the editable list of keys to look up data from an attachment's metadata. 3502 * 3503 * @since 3.9.0 3504 * 3505 * @param array $fields Key/value pairs of field keys to labels. 3506 * @param WP_Post $attachment Attachment object. 3507 * @param string $context The context. Accepts 'edit', 'display'. Default 'display'. 3508 */ 3509 return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context ); 3510 } 3511 /** 3512 * Builds the Audio shortcode output. 3513 * 3514 * This implements the functionality of the Audio Shortcode for displaying 3515 * WordPress mp3s in a post. 3516 * 3517 * @since 3.6.0 3518 * @since 6.8.0 Added the 'muted' attribute. 3519 * 3520 * @param array $attr { 3521 * Attributes of the audio shortcode. 3522 * 3523 * @type string $src URL to the source of the audio file. Default empty. 3524 * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty. 3525 * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty. 3526 * @type string $muted The 'muted' attribute for the `<audio>` element. Default 'false'. 3527 * @type string $preload The 'preload' attribute for the `<audio>` element. Default 'none'. 3528 * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'. 3529 * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%;'. 3530 * } 3531 * @param string $content Shortcode content. 3532 * @return string|null HTML content to display audio. 3533 */ 3534 function wp_audio_shortcode( $attr, $content = '' ) { 3535 $post_id = get_post() ? get_the_ID() : 0; 3536 3537 static $instance = 0; 3538 ++$instance; 3539 3540 /** 3541 * Filters the default audio shortcode output. 3542 * 3543 * If the filtered output isn't empty, it will be used instead of generating the default audio template. 3544 * 3545 * @since 3.6.0 3546 * 3547 * @param string $html Empty variable to be replaced with shortcode markup. 3548 * @param array $attr Attributes of the shortcode. See {@see wp_audio_shortcode()}. 3549 * @param string $content Shortcode content. 3550 * @param int $instance Unique numeric ID of this audio shortcode instance. 3551 */ 3552 $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance ); 3553 3554 if ( '' !== $override ) { 3555 return $override; 3556 } 3557 3558 $audio = null; 3559 3560 $default_types = wp_get_audio_extensions(); 3561 $defaults_atts = array( 3562 'src' => '', 3563 'loop' => '', 3564 'autoplay' => '', 3565 'muted' => 'false', 3566 'preload' => 'none', 3567 'class' => 'wp-audio-shortcode', 3568 'style' => 'width: 100%;', 3569 ); 3570 foreach ( $default_types as $type ) { 3571 $defaults_atts[ $type ] = ''; 3572 } 3573 3574 $atts = shortcode_atts( $defaults_atts, $attr, 'audio' ); 3575 3576 $primary = false; 3577 if ( ! empty( $atts['src'] ) ) { 3578 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() ); 3579 3580 if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) { 3581 return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) ); 3582 } 3583 3584 $primary = true; 3585 array_unshift( $default_types, 'src' ); 3586 } else { 3587 foreach ( $default_types as $ext ) { 3588 if ( ! empty( $atts[ $ext ] ) ) { 3589 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() ); 3590 3591 if ( strtolower( $type['ext'] ) === $ext ) { 3592 $primary = true; 3593 } 3594 } 3595 } 3596 } 3597 3598 if ( ! $primary ) { 3599 $audios = get_attached_media( 'audio', $post_id ); 3600 3601 if ( empty( $audios ) ) { 3602 return null; 3603 } 3604 3605 $audio = reset( $audios ); 3606 $atts['src'] = wp_get_attachment_url( $audio->ID ); 3607 3608 if ( empty( $atts['src'] ) ) { 3609 return null; 3610 } 3611 3612 array_unshift( $default_types, 'src' ); 3613 } 3614 3615 /** 3616 * Filters the media library used for the audio shortcode. 3617 * 3618 * @since 3.6.0 3619 * 3620 * @param string $library Media library used for the audio shortcode. 3621 */ 3622 $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' ); 3623 3624 if ( 'mediaelement' === $library && did_action( 'init' ) ) { 3625 wp_enqueue_style( 'wp-mediaelement' ); 3626 wp_enqueue_script( 'wp-mediaelement' ); 3627 } 3628 3629 /** 3630 * Filters the class attribute for the audio shortcode output container. 3631 * 3632 * @since 3.6.0 3633 * @since 4.9.0 The `$atts` parameter was added. 3634 * 3635 * @param string $class CSS class or list of space-separated classes. 3636 * @param array $atts Array of audio shortcode attributes. 3637 */ 3638 $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'], $atts ); 3639 3640 $html_atts = array( 3641 'class' => $atts['class'], 3642 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ), 3643 'loop' => wp_validate_boolean( $atts['loop'] ), 3644 'autoplay' => wp_validate_boolean( $atts['autoplay'] ), 3645 'muted' => wp_validate_boolean( $atts['muted'] ), 3646 'preload' => $atts['preload'], 3647 'style' => $atts['style'], 3648 ); 3649 3650 // These ones should just be omitted altogether if they are blank. 3651 foreach ( array( 'loop', 'autoplay', 'preload', 'muted' ) as $a ) { 3652 if ( empty( $html_atts[ $a ] ) ) { 3653 unset( $html_atts[ $a ] ); 3654 } 3655 } 3656 3657 $attr_strings = array(); 3658 3659 foreach ( $html_atts as $attribute_name => $attribute_value ) { 3660 if ( in_array( $attribute_name, array( 'loop', 'autoplay', 'muted' ), true ) && true === $attribute_value ) { 3661 // Add boolean attributes without a value. 3662 $attr_strings[] = esc_attr( $attribute_name ); 3663 } elseif ( 'preload' === $attribute_name && ! empty( $attribute_value ) ) { 3664 // Handle the preload attribute with specific allowed values. 3665 $allowed_preload_values = array( 'none', 'metadata', 'auto' ); 3666 if ( in_array( $attribute_value, $allowed_preload_values, true ) ) { 3667 $attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) ); 3668 } 3669 } else { 3670 // For other attributes, include the value. 3671 $attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) ); 3672 } 3673 } 3674 3675 $html = sprintf( '<audio %s controls="controls">', implode( ' ', $attr_strings ) ); 3676 $fileurl = ''; 3677 $source = '<source type="%s" src="%s" />'; 3678 3679 foreach ( $default_types as $fallback ) { 3680 if ( ! empty( $atts[ $fallback ] ) ) { 3681 if ( empty( $fileurl ) ) { 3682 $fileurl = $atts[ $fallback ]; 3683 } 3684 3685 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() ); 3686 $url = add_query_arg( '_', $instance, $atts[ $fallback ] ); 3687 $html .= sprintf( $source, $type['type'], esc_url( $url ) ); 3688 } 3689 } 3690 3691 if ( 'mediaelement' === $library ) { 3692 $html .= wp_mediaelement_fallback( $fileurl ); 3693 } 3694 3695 $html .= '</audio>'; 3696 3697 /** 3698 * Filters the audio shortcode output. 3699 * 3700 * @since 3.6.0 3701 * 3702 * @param string $html Audio shortcode HTML output. 3703 * @param array $atts Array of audio shortcode attributes. 3704 * @param string $audio Audio file. 3705 * @param int $post_id Post ID. 3706 * @param string $library Media library used for the audio shortcode. 3707 */ 3708 return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library ); 3709 } 3710 add_shortcode( 'audio', 'wp_audio_shortcode' ); 3711 3712 /** 3713 * Returns a filtered list of supported video formats. 3714 * 3715 * @since 3.6.0 3716 * 3717 * @return string[] List of supported video formats. 3718 */ 3719 function wp_get_video_extensions() { 3720 /** 3721 * Filters the list of supported video formats. 3722 * 3723 * @since 3.6.0 3724 * 3725 * @param string[] $extensions An array of supported video formats. Defaults are 3726 * 'mp4', 'm4v', 'webm', 'ogv', 'flv'. 3727 */ 3728 return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) ); 3729 } 3730 3731 /** 3732 * Builds the Video shortcode output. 3733 * 3734 * This implements the functionality of the Video Shortcode for displaying 3735 * WordPress mp4s in a post. 3736 * 3737 * @since 3.6.0 3738 * 3739 * @global int $content_width 3740 * 3741 * @param array $attr { 3742 * Attributes of the shortcode. 3743 * 3744 * @type string $src URL to the source of the video file. Default empty. 3745 * @type int $height Height of the video embed in pixels. Default 360. 3746 * @type int $width Width of the video embed in pixels. Default $content_width or 640. 3747 * @type string $poster The 'poster' attribute for the `<video>` element. Default empty. 3748 * @type string $loop The 'loop' attribute for the `<video>` element. Default empty. 3749 * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty. 3750 * @type string $muted The 'muted' attribute for the `<video>` element. Default false. 3751 * @type string $preload The 'preload' attribute for the `<video>` element. 3752 * Default 'metadata'. 3753 * @type string $class The 'class' attribute for the `<video>` element. 3754 * Default 'wp-video-shortcode'. 3755 * } 3756 * @param string $content Shortcode content. 3757 * @return string|null HTML content to display video. 3758 */ 3759 function wp_video_shortcode( $attr, $content = '' ) { 3760 global $content_width; 3761 $post_id = get_post() ? get_the_ID() : 0; 3762 3763 static $instance = 0; 3764 ++$instance; 3765 3766 /** 3767 * Filters the default video shortcode output. 3768 * 3769 * If the filtered output isn't empty, it will be used instead of generating 3770 * the default video template. 3771 * 3772 * @since 3.6.0 3773 * 3774 * @see wp_video_shortcode() 3775 * 3776 * @param string $html Empty variable to be replaced with shortcode markup. 3777 * @param array $attr Attributes of the shortcode. See {@see wp_video_shortcode()}. 3778 * @param string $content Video shortcode content. 3779 * @param int $instance Unique numeric ID of this video shortcode instance. 3780 */ 3781 $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance ); 3782 3783 if ( '' !== $override ) { 3784 return $override; 3785 } 3786 3787 $video = null; 3788 3789 $default_types = wp_get_video_extensions(); 3790 $defaults_atts = array( 3791 'src' => '', 3792 'poster' => '', 3793 'loop' => '', 3794 'autoplay' => '', 3795 'muted' => 'false', 3796 'preload' => 'metadata', 3797 'width' => 640, 3798 'height' => 360, 3799 'class' => 'wp-video-shortcode', 3800 ); 3801 3802 foreach ( $default_types as $type ) { 3803 $defaults_atts[ $type ] = ''; 3804 } 3805 3806 $atts = shortcode_atts( $defaults_atts, $attr, 'video' ); 3807 3808 if ( is_admin() ) { 3809 // Shrink the video so it isn't huge in the admin. 3810 if ( $atts['width'] > $defaults_atts['width'] ) { 3811 $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] ); 3812 $atts['width'] = $defaults_atts['width']; 3813 } 3814 } else { 3815 // If the video is bigger than the theme. 3816 if ( ! empty( $content_width ) && $atts['width'] > $content_width ) { 3817 $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] ); 3818 $atts['width'] = $content_width; 3819 } 3820 } 3821 3822 $is_vimeo = false; 3823 $is_youtube = false; 3824 $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#'; 3825 $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#'; 3826 3827 $primary = false; 3828 if ( ! empty( $atts['src'] ) ) { 3829 $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) ); 3830 $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) ); 3831 3832 if ( ! $is_youtube && ! $is_vimeo ) { 3833 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() ); 3834 3835 if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) { 3836 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) ); 3837 } 3838 } 3839 3840 if ( $is_vimeo ) { 3841 wp_enqueue_script( 'mediaelement-vimeo' ); 3842 } 3843 3844 $primary = true; 3845 array_unshift( $default_types, 'src' ); 3846 } else { 3847 foreach ( $default_types as $ext ) { 3848 if ( ! empty( $atts[ $ext ] ) ) { 3849 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() ); 3850 if ( strtolower( $type['ext'] ) === $ext ) { 3851 $primary = true; 3852 } 3853 } 3854 } 3855 } 3856 3857 if ( ! $primary ) { 3858 $videos = get_attached_media( 'video', $post_id ); 3859 if ( empty( $videos ) ) { 3860 return null; 3861 } 3862 3863 $video = reset( $videos ); 3864 $atts['src'] = wp_get_attachment_url( $video->ID ); 3865 if ( empty( $atts['src'] ) ) { 3866 return null; 3867 } 3868 3869 array_unshift( $default_types, 'src' ); 3870 } 3871 3872 /** 3873 * Filters the media library used for the video shortcode. 3874 * 3875 * @since 3.6.0 3876 * 3877 * @param string $library Media library used for the video shortcode. 3878 */ 3879 $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' ); 3880 if ( 'mediaelement' === $library && did_action( 'init' ) ) { 3881 wp_enqueue_style( 'wp-mediaelement' ); 3882 wp_enqueue_script( 'wp-mediaelement' ); 3883 wp_enqueue_script( 'mediaelement-vimeo' ); 3884 } 3885 3886 /* 3887 * MediaElement.js has issues with some URL formats for Vimeo and YouTube, 3888 * so update the URL to prevent the ME.js player from breaking. 3889 */ 3890 if ( 'mediaelement' === $library ) { 3891 if ( $is_youtube ) { 3892 // Remove `feature` query arg and force SSL - see #40866. 3893 $atts['src'] = remove_query_arg( 'feature', $atts['src'] ); 3894 $atts['src'] = set_url_scheme( $atts['src'], 'https' ); 3895 } elseif ( $is_vimeo ) { 3896 // Remove all query arguments and force SSL - see #40866. 3897 $parsed_vimeo_url = wp_parse_url( $atts['src'] ); 3898 $vimeo_src = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path']; 3899 3900 // Add loop param for mejs bug - see #40977, not needed after #39686. 3901 $loop = $atts['loop'] ? '1' : '0'; 3902 $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src ); 3903 } 3904 } 3905 3906 /** 3907 * Filters the class attribute for the video shortcode output container. 3908 * 3909 * @since 3.6.0 3910 * @since 4.9.0 The `$atts` parameter was added. 3911 * 3912 * @param string $class CSS class or list of space-separated classes. 3913 * @param array $atts Array of video shortcode attributes. 3914 */ 3915 $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'], $atts ); 3916 3917 $html_atts = array( 3918 'class' => $atts['class'], 3919 'id' => sprintf( 'video-%d-%d', $post_id, $instance ), 3920 'width' => absint( $atts['width'] ), 3921 'height' => absint( $atts['height'] ), 3922 'poster' => esc_url( $atts['poster'] ), 3923 'loop' => wp_validate_boolean( $atts['loop'] ), 3924 'autoplay' => wp_validate_boolean( $atts['autoplay'] ), 3925 'muted' => wp_validate_boolean( $atts['muted'] ), 3926 'preload' => $atts['preload'], 3927 ); 3928 3929 // These ones should just be omitted altogether if they are blank. 3930 foreach ( array( 'poster', 'loop', 'autoplay', 'preload', 'muted' ) as $a ) { 3931 if ( empty( $html_atts[ $a ] ) ) { 3932 unset( $html_atts[ $a ] ); 3933 } 3934 } 3935 3936 $attr_strings = array(); 3937 foreach ( $html_atts as $attribute_name => $attribute_value ) { 3938 if ( in_array( $attribute_name, array( 'loop', 'autoplay', 'muted' ), true ) && true === $attribute_value ) { 3939 // Add boolean attributes without their value for true. 3940 $attr_strings[] = esc_attr( $attribute_name ); 3941 } elseif ( 'preload' === $attribute_name && ! empty( $attribute_value ) ) { 3942 // Handle the preload attribute with specific allowed values. 3943 $allowed_preload_values = array( 'none', 'metadata', 'auto' ); 3944 if ( in_array( $attribute_value, $allowed_preload_values, true ) ) { 3945 $attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) ); 3946 } 3947 } elseif ( ! empty( $attribute_value ) ) { 3948 // For non-boolean attributes, add them with their value. 3949 $attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) ); 3950 } 3951 } 3952 3953 $html = sprintf( '<video %s controls="controls">', implode( ' ', $attr_strings ) ); 3954 $fileurl = ''; 3955 $source = '<source type="%s" src="%s" />'; 3956 3957 foreach ( $default_types as $fallback ) { 3958 if ( ! empty( $atts[ $fallback ] ) ) { 3959 if ( empty( $fileurl ) ) { 3960 $fileurl = $atts[ $fallback ]; 3961 } 3962 if ( 'src' === $fallback && $is_youtube ) { 3963 $type = array( 'type' => 'video/youtube' ); 3964 } elseif ( 'src' === $fallback && $is_vimeo ) { 3965 $type = array( 'type' => 'video/vimeo' ); 3966 } else { 3967 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() ); 3968 } 3969 $url = add_query_arg( '_', $instance, $atts[ $fallback ] ); 3970 $html .= sprintf( $source, $type['type'], esc_url( $url ) ); 3971 } 3972 } 3973 3974 if ( ! empty( $content ) ) { 3975 if ( str_contains( $content, "\n" ) ) { 3976 $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content ); 3977 } 3978 $html .= trim( $content ); 3979 } 3980 3981 if ( 'mediaelement' === $library ) { 3982 $html .= wp_mediaelement_fallback( $fileurl ); 3983 } 3984 $html .= '</video>'; 3985 3986 $width_rule = ''; 3987 if ( ! empty( $atts['width'] ) ) { 3988 $width_rule = sprintf( 'width: %dpx;', $atts['width'] ); 3989 } 3990 $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html ); 3991 3992 /** 3993 * Filters the output of the video shortcode. 3994 * 3995 * @since 3.6.0 3996 * 3997 * @param string $output Video shortcode HTML output. 3998 * @param array $atts Array of video shortcode attributes. 3999 * @param string $video Video file. 4000 * @param int $post_id Post ID. 4001 * @param string $library Media library used for the video shortcode. 4002 */ 4003 return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library ); 4004 } 4005 add_shortcode( 'video', 'wp_video_shortcode' ); 4006 4007 /** 4008 * Gets the previous image link that has the same post parent. 4009 * 4010 * @since 5.8.0 4011 * 4012 * @see get_adjacent_image_link() 4013 * 4014 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 4015 * of width and height values in pixels (in that order). Default 'thumbnail'. 4016 * @param string|false $text Optional. Link text. Default false. 4017 * @return string Markup for previous image link. 4018 */ 4019 function get_previous_image_link( $size = 'thumbnail', $text = false ) { 4020 return get_adjacent_image_link( true, $size, $text ); 4021 } 4022 4023 /** 4024 * Displays previous image link that has the same post parent. 4025 * 4026 * @since 2.5.0 4027 * 4028 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 4029 * of width and height values in pixels (in that order). Default 'thumbnail'. 4030 * @param string|false $text Optional. Link text. Default false. 4031 */ 4032 function previous_image_link( $size = 'thumbnail', $text = false ) { 4033 echo get_previous_image_link( $size, $text ); 4034 } 4035 4036 /** 4037 * Gets the next image link that has the same post parent. 4038 * 4039 * @since 5.8.0 4040 * 4041 * @see get_adjacent_image_link() 4042 * 4043 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 4044 * of width and height values in pixels (in that order). Default 'thumbnail'. 4045 * @param string|false $text Optional. Link text. Default false. 4046 * @return string Markup for next image link. 4047 */ 4048 function get_next_image_link( $size = 'thumbnail', $text = false ) { 4049 return get_adjacent_image_link( false, $size, $text ); 4050 } 4051 4052 /** 4053 * Displays next image link that has the same post parent. 4054 * 4055 * @since 2.5.0 4056 * 4057 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 4058 * of width and height values in pixels (in that order). Default 'thumbnail'. 4059 * @param string|false $text Optional. Link text. Default false. 4060 */ 4061 function next_image_link( $size = 'thumbnail', $text = false ) { 4062 echo get_next_image_link( $size, $text ); 4063 } 4064 4065 /** 4066 * Gets the next or previous image link that has the same post parent. 4067 * 4068 * Retrieves the current attachment object from the $post global. 4069 * 4070 * @since 5.8.0 4071 * 4072 * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true. 4073 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 4074 * of width and height values in pixels (in that order). Default 'thumbnail'. 4075 * @param bool $text Optional. Link text. Default false. 4076 * @return string Markup for image link. 4077 */ 4078 function get_adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) { 4079 $post = get_post(); 4080 $attachments = array_values( 4081 get_children( 4082 array( 4083 'post_parent' => $post->post_parent, 4084 'post_status' => 'inherit', 4085 'post_type' => 'attachment', 4086 'post_mime_type' => 'image', 4087 'order' => 'ASC', 4088 'orderby' => 'menu_order ID', 4089 ) 4090 ) 4091 ); 4092 4093 foreach ( $attachments as $k => $attachment ) { 4094 if ( (int) $attachment->ID === (int) $post->ID ) { 4095 break; 4096 } 4097 } 4098 4099 $output = ''; 4100 $attachment_id = 0; 4101 4102 if ( $attachments ) { 4103 $k = $prev ? $k - 1 : $k + 1; 4104 4105 if ( isset( $attachments[ $k ] ) ) { 4106 $attachment_id = $attachments[ $k ]->ID; 4107 $attr = array( 'alt' => get_the_title( $attachment_id ) ); 4108 $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text, $attr ); 4109 } 4110 } 4111 4112 $adjacent = $prev ? 'previous' : 'next'; 4113 4114 /** 4115 * Filters the adjacent image link. 4116 * 4117 * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency, 4118 * either 'next', or 'previous'. 4119 * 4120 * Possible hook names include: 4121 * 4122 * - `next_image_link` 4123 * - `previous_image_link` 4124 * 4125 * @since 3.5.0 4126 * 4127 * @param string $output Adjacent image HTML markup. 4128 * @param int $attachment_id Attachment ID 4129 * @param string|int[] $size Requested image size. Can be any registered image size name, or 4130 * an array of width and height values in pixels (in that order). 4131 * @param string $text Link text. 4132 */ 4133 return apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text ); 4134 } 4135 4136 /** 4137 * Displays next or previous image link that has the same post parent. 4138 * 4139 * Retrieves the current attachment object from the $post global. 4140 * 4141 * @since 2.5.0 4142 * 4143 * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true. 4144 * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array 4145 * of width and height values in pixels (in that order). Default 'thumbnail'. 4146 * @param bool $text Optional. Link text. Default false. 4147 */ 4148 function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) { 4149 echo get_adjacent_image_link( $prev, $size, $text ); 4150 } 4151 4152 /** 4153 * Retrieves taxonomies attached to given the attachment. 4154 * 4155 * @since 2.5.0 4156 * @since 4.7.0 Introduced the `$output` parameter. 4157 * 4158 * @param int|array|object $attachment Attachment ID, data array, or data object. 4159 * @param string $output Output type. 'names' to return an array of taxonomy names, 4160 * or 'objects' to return an array of taxonomy objects. 4161 * Default is 'names'. 4162 * @return string[]|WP_Taxonomy[] List of taxonomies or taxonomy names. Empty array on failure. 4163 */ 4164 function get_attachment_taxonomies( $attachment, $output = 'names' ) { 4165 if ( is_int( $attachment ) ) { 4166 $attachment = get_post( $attachment ); 4167 } elseif ( is_array( $attachment ) ) { 4168 $attachment = (object) $attachment; 4169 } 4170 4171 if ( ! is_object( $attachment ) ) { 4172 return array(); 4173 } 4174 4175 $file = get_attached_file( $attachment->ID ); 4176 $filename = wp_basename( $file ); 4177 4178 $objects = array( 'attachment' ); 4179 4180 if ( str_contains( $filename, '.' ) ) { 4181 $objects[] = 'attachment:' . substr( $filename, strrpos( $filename, '.' ) + 1 ); 4182 } 4183 4184 if ( ! empty( $attachment->post_mime_type ) ) { 4185 $objects[] = 'attachment:' . $attachment->post_mime_type; 4186 4187 if ( str_contains( $attachment->post_mime_type, '/' ) ) { 4188 foreach ( explode( '/', $attachment->post_mime_type ) as $token ) { 4189 if ( ! empty( $token ) ) { 4190 $objects[] = "attachment:$token"; 4191 } 4192 } 4193 } 4194 } 4195 4196 $taxonomies = array(); 4197 4198 foreach ( $objects as $object ) { 4199 $taxes = get_object_taxonomies( $object, $output ); 4200 4201 if ( $taxes ) { 4202 $taxonomies = array_merge( $taxonomies, $taxes ); 4203 } 4204 } 4205 4206 if ( 'names' === $output ) { 4207 $taxonomies = array_unique( $taxonomies ); 4208 } 4209 4210 return $taxonomies; 4211 } 4212 4213 /** 4214 * Retrieves all of the taxonomies that are registered for attachments. 4215 * 4216 * Handles mime-type-specific taxonomies such as attachment:image and attachment:video. 4217 * 4218 * @since 3.5.0 4219 * 4220 * @see get_taxonomies() 4221 * 4222 * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'. 4223 * Default 'names'. 4224 * @return string[]|WP_Taxonomy[] Array of names or objects of registered taxonomies for attachments. 4225 */ 4226 function get_taxonomies_for_attachments( $output = 'names' ) { 4227 $taxonomies = array(); 4228 4229 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) { 4230 foreach ( $taxonomy->object_type as $object_type ) { 4231 if ( 'attachment' === $object_type || str_starts_with( $object_type, 'attachment:' ) ) { 4232 if ( 'names' === $output ) { 4233 $taxonomies[] = $taxonomy->name; 4234 } else { 4235 $taxonomies[ $taxonomy->name ] = $taxonomy; 4236 } 4237 break; 4238 } 4239 } 4240 } 4241 4242 return $taxonomies; 4243 } 4244 4245 /** 4246 * Determines whether the value is an acceptable type for GD image functions. 4247 * 4248 * In PHP 8.0, the GD extension uses GdImage objects for its data structures. 4249 * This function checks if the passed value is either a GdImage object instance 4250 * or a resource of type `gd`. Any other type will return false. 4251 * 4252 * @since 5.6.0 4253 * 4254 * @param resource|GdImage|false $image A value to check the type for. 4255 * @return bool True if `$image` is either a GD image resource or a GdImage instance, 4256 * false otherwise. 4257 */ 4258 function is_gd_image( $image ) { 4259 if ( $image instanceof GdImage // @phpstan-ignore class.notFound (Only available with PHP8+.) 4260 || is_resource( $image ) && 'gd' === get_resource_type( $image ) 4261 ) { 4262 return true; 4263 } 4264 4265 return false; 4266 } 4267 4268 /** 4269 * Creates a new GD image resource with transparency support. 4270 * 4271 * @todo Deprecate if possible. 4272 * 4273 * @since 2.9.0 4274 * 4275 * @param int $width Image width in pixels. 4276 * @param int $height Image height in pixels. 4277 * @return resource|GdImage|false The GD image resource or GdImage instance on success. 4278 * False on failure. 4279 */ 4280 function wp_imagecreatetruecolor( $width, $height ) { 4281 $img = imagecreatetruecolor( $width, $height ); 4282 4283 if ( is_gd_image( $img ) 4284 && function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) 4285 ) { 4286 imagealphablending( $img, false ); 4287 imagesavealpha( $img, true ); 4288 } 4289 4290 return $img; 4291 } 4292 4293 /** 4294 * Based on a supplied width/height example, returns the biggest possible dimensions based on the max width/height. 4295 * 4296 * @since 2.9.0 4297 * 4298 * @see wp_constrain_dimensions() 4299 * 4300 * @param int $example_width The width of an example embed. 4301 * @param int $example_height The height of an example embed. 4302 * @param int $max_width The maximum allowed width. 4303 * @param int $max_height The maximum allowed height. 4304 * @return int[] { 4305 * An array of maximum width and height values. 4306 * 4307 * @type int $0 The maximum width in pixels. 4308 * @type int $1 The maximum height in pixels. 4309 * } 4310 */ 4311 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) { 4312 $example_width = (int) $example_width; 4313 $example_height = (int) $example_height; 4314 $max_width = (int) $max_width; 4315 $max_height = (int) $max_height; 4316 4317 return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height ); 4318 } 4319 4320 /** 4321 * Determines the maximum upload size allowed in php.ini. 4322 * 4323 * @since 2.5.0 4324 * 4325 * @return int Allowed upload size. 4326 */ 4327 function wp_max_upload_size() { 4328 $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) ); 4329 $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) ); 4330 4331 /** 4332 * Filters the maximum upload size allowed in php.ini. 4333 * 4334 * @since 2.5.0 4335 * 4336 * @param int $size Max upload size limit in bytes. 4337 * @param int $u_bytes Maximum upload filesize in bytes. 4338 * @param int $p_bytes Maximum size of POST data in bytes. 4339 */ 4340 return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes ); 4341 } 4342 4343 /** 4344 * Returns a WP_Image_Editor instance and loads file into it. 4345 * 4346 * @since 3.5.0 4347 * 4348 * @param string $path Path to the file to load. 4349 * @param array $args Optional. Additional arguments for retrieving the image editor. 4350 * Default empty array. 4351 * @return WP_Image_Editor|WP_Error The WP_Image_Editor object on success, 4352 * a WP_Error object otherwise. 4353 */ 4354 function wp_get_image_editor( $path, $args = array() ) { 4355 $args['path'] = $path; 4356 4357 // If the mime type is not set in args, try to extract and set it from the file. 4358 if ( ! isset( $args['mime_type'] ) ) { 4359 $file_info = wp_check_filetype( $args['path'] ); 4360 4361 /* 4362 * If $file_info['type'] is false, then we let the editor attempt to 4363 * figure out the file type, rather than forcing a failure based on extension. 4364 */ 4365 if ( isset( $file_info ) && $file_info['type'] ) { 4366 $args['mime_type'] = $file_info['type']; 4367 } 4368 } 4369 4370 // Check and set the output mime type mapped to the input type. 4371 if ( isset( $args['mime_type'] ) ) { 4372 $output_format = wp_get_image_editor_output_format( $path, $args['mime_type'] ); 4373 if ( isset( $output_format[ $args['mime_type'] ] ) ) { 4374 $args['output_mime_type'] = $output_format[ $args['mime_type'] ]; 4375 } 4376 } 4377 4378 $implementation = _wp_image_editor_choose( $args ); 4379 4380 if ( $implementation ) { 4381 $editor = new $implementation( $path ); 4382 $loaded = $editor->load(); 4383 4384 if ( is_wp_error( $loaded ) ) { 4385 return $loaded; 4386 } 4387 4388 return $editor; 4389 } 4390 4391 return new WP_Error( 'image_no_editor', __( 'No editor could be selected.' ) ); 4392 } 4393 4394 /** 4395 * Tests whether there is an editor that supports a given mime type or methods. 4396 * 4397 * @since 3.5.0 4398 * 4399 * @param string|array $args Optional. Array of arguments to retrieve the image editor supports. 4400 * Default empty array. 4401 * @return bool True if an eligible editor is found; false otherwise. 4402 */ 4403 function wp_image_editor_supports( $args = array() ) { 4404 return (bool) _wp_image_editor_choose( $args ); 4405 } 4406 4407 /** 4408 * Tests which editors are capable of supporting the request. 4409 * 4410 * @ignore 4411 * @since 3.5.0 4412 * 4413 * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array. 4414 * @return string|false Class name for the first editor that claims to support the request. 4415 * False if no editor claims to support the request. 4416 */ 4417 function _wp_image_editor_choose( $args = array() ) { 4418 require_once ABSPATH . WPINC . '/class-wp-image-editor.php'; 4419 require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php'; 4420 require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php'; 4421 require_once ABSPATH . WPINC . '/class-avif-info.php'; 4422 /** 4423 * Filters the list of image editing library classes. 4424 * 4425 * @since 3.5.0 4426 * 4427 * @param string[] $image_editors Array of available image editor class names. Defaults are 4428 * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'. 4429 */ 4430 $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) ); 4431 4432 $editors = wp_cache_get( 'wp_image_editor_choose', 'image_editor' ); 4433 4434 if ( ! is_array( $editors ) ) { 4435 $editors = array(); 4436 } 4437 4438 // Cache the chosen editor implementation based on specific args and available implementations. 4439 $cache_key = md5( serialize( array( $args, $implementations ) ) ); 4440 4441 if ( isset( $editors[ $cache_key ] ) ) { 4442 return $editors[ $cache_key ]; 4443 } 4444 4445 // Assume no support until a capable implementation is identified. 4446 $editor = false; 4447 4448 foreach ( $implementations as $implementation ) { 4449 if ( ! call_user_func( array( $implementation, 'test' ), $args ) ) { 4450 continue; 4451 } 4452 4453 // Implementation should support the passed mime type. 4454 if ( isset( $args['mime_type'] ) && 4455 ! call_user_func( 4456 array( $implementation, 'supports_mime_type' ), 4457 $args['mime_type'] 4458 ) ) { 4459 continue; 4460 } 4461 4462 // Implementation should support requested methods. 4463 if ( isset( $args['methods'] ) && 4464 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) { 4465 4466 continue; 4467 } 4468 4469 // Implementation should ideally support the output mime type as well if set and different than the passed type. 4470 if ( 4471 isset( $args['mime_type'] ) && 4472 isset( $args['output_mime_type'] ) && 4473 $args['mime_type'] !== $args['output_mime_type'] && 4474 ! call_user_func( array( $implementation, 'supports_mime_type' ), $args['output_mime_type'] ) 4475 ) { 4476 /* 4477 * This implementation supports the input type but not the output type. 4478 * Keep looking to see if we can find an implementation that supports both. 4479 */ 4480 $editor = $implementation; 4481 continue; 4482 } 4483 4484 // Favor the implementation that supports both input and output mime types. 4485 $editor = $implementation; 4486 break; 4487 } 4488 4489 $editors[ $cache_key ] = $editor; 4490 4491 wp_cache_set( 'wp_image_editor_choose', $editors, 'image_editor', DAY_IN_SECONDS ); 4492 4493 return $editor; 4494 } 4495 4496 /** 4497 * Prints default Plupload arguments. 4498 * 4499 * @since 3.4.0 4500 */ 4501 function wp_plupload_default_settings() { 4502 $wp_scripts = wp_scripts(); 4503 4504 $data = $wp_scripts->get_data( 'wp-plupload', 'data' ); 4505 if ( $data && str_contains( $data, '_wpPluploadSettings' ) ) { 4506 return; 4507 } 4508 4509 $max_upload_size = wp_max_upload_size(); 4510 $allowed_extensions = array_keys( get_allowed_mime_types() ); 4511 $extensions = array(); 4512 foreach ( $allowed_extensions as $extension ) { 4513 $extensions = array_merge( $extensions, explode( '|', $extension ) ); 4514 } 4515 4516 /* 4517 * Since 4.9 the `runtimes` setting is hardcoded in our version of Plupload to `html5,html4`, 4518 * and the `flash_swf_url` and `silverlight_xap_url` are not used. 4519 */ 4520 $defaults = array( 4521 'file_data_name' => 'async-upload', // Key passed to $_FILE. 4522 'url' => admin_url( 'async-upload.php', 'relative' ), 4523 'filters' => array( 4524 'max_file_size' => $max_upload_size . 'b', 4525 'mime_types' => array( array( 'extensions' => implode( ',', $extensions ) ) ), 4526 ), 4527 ); 4528 4529 /* 4530 * Currently only iOS Safari supports multiple files uploading, 4531 * but iOS 7.x has a bug that prevents uploading of videos when enabled. 4532 * See #29602. 4533 */ 4534 if ( wp_is_mobile() 4535 && str_contains( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) 4536 && str_contains( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) 4537 ) { 4538 $defaults['multi_selection'] = false; 4539 } 4540 4541 // Check if WebP images can be edited. 4542 if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/webp' ) ) ) { 4543 $defaults['webp_upload_error'] = true; 4544 } 4545 4546 // Check if AVIF images can be edited. 4547 if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/avif' ) ) ) { 4548 $defaults['avif_upload_error'] = true; 4549 } 4550 4551 // Check if HEIC images can be edited. 4552 if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/heic' ) ) ) { 4553 $defaults['heic_upload_error'] = true; 4554 } 4555 4556 /** 4557 * Filters the Plupload default settings. 4558 * 4559 * @since 3.4.0 4560 * 4561 * @param array $defaults Default Plupload settings array. 4562 */ 4563 $defaults = apply_filters( 'plupload_default_settings', $defaults ); 4564 4565 $params = array( 4566 'action' => 'upload-attachment', 4567 ); 4568 4569 /** 4570 * Filters the Plupload default parameters. 4571 * 4572 * @since 3.4.0 4573 * 4574 * @param array $params Default Plupload parameters array. 4575 */ 4576 $params = apply_filters( 'plupload_default_params', $params ); 4577 4578 $params['_wpnonce'] = wp_create_nonce( 'media-form' ); 4579 4580 $defaults['multipart_params'] = $params; 4581 4582 $settings = array( 4583 'defaults' => $defaults, 4584 'browser' => array( 4585 'mobile' => wp_is_mobile(), 4586 'supported' => _device_can_upload(), 4587 ), 4588 'limitExceeded' => is_multisite() && ! is_upload_space_available(), 4589 ); 4590 4591 $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ) . ';'; 4592 4593 if ( $data ) { 4594 $script = "$data\n$script"; 4595 } 4596 4597 $wp_scripts->add_data( 'wp-plupload', 'data', $script ); 4598 } 4599 4600 /** 4601 * Prepares an attachment post object for JS, where it is expected 4602 * to be JSON-encoded and fit into an Attachment model. 4603 * 4604 * @since 3.5.0 4605 * 4606 * @param int|WP_Post $attachment Attachment ID or object. 4607 * @return array|null { 4608 * Array of attachment details, or null if the parameter does not correspond to an attachment. 4609 * 4610 * @type string $alt Alt text of the attachment. 4611 * @type string $author ID of the attachment author, as a string. 4612 * @type string $authorName Name of the attachment author. 4613 * @type string $caption Caption for the attachment. 4614 * @type array $compat Containing item and meta. 4615 * @type string $context Context, whether it's used as the site icon for example. 4616 * @type int $date Uploaded date, timestamp in milliseconds. 4617 * @type string $dateFormatted Formatted date (e.g. June 29, 2018). 4618 * @type string $description Description of the attachment. 4619 * @type string $editLink URL to the edit page for the attachment. 4620 * @type string $filename File name of the attachment. 4621 * @type string $filesizeHumanReadable Filesize of the attachment in human readable format (e.g. 1 MB). 4622 * @type int $filesizeInBytes Filesize of the attachment in bytes. 4623 * @type int $height If the attachment is an image, represents the height of the image in pixels. 4624 * @type string $icon Icon URL of the attachment (e.g. /wp-includes/images/media/archive.png). 4625 * @type int $id ID of the attachment. 4626 * @type string $link URL to the attachment. 4627 * @type int $menuOrder Menu order of the attachment post. 4628 * @type array $meta Meta data for the attachment. 4629 * @type string $mime Mime type of the attachment (e.g. image/jpeg or application/zip). 4630 * @type int $modified Last modified, timestamp in milliseconds. 4631 * @type string $name Name, same as title of the attachment. 4632 * @type array $nonces Nonces for update, delete and edit. 4633 * @type string $orientation If the attachment is an image, represents the image orientation 4634 * (landscape or portrait). 4635 * @type array $sizes If the attachment is an image, contains an array of arrays 4636 * for the images sizes: thumbnail, medium, large, and full. 4637 * @type string $status Post status of the attachment (usually 'inherit'). 4638 * @type string $subtype Mime subtype of the attachment (usually the last part, e.g. jpeg or zip). 4639 * @type string $title Title of the attachment (usually slugified file name without the extension). 4640 * @type string $type Type of the attachment (usually first part of the mime type, e.g. image). 4641 * @type int $uploadedTo Parent post to which the attachment was uploaded. 4642 * @type string $uploadedToLink URL to the edit page of the parent post of the attachment. 4643 * @type string $uploadedToTitle Post title of the parent of the attachment. 4644 * @type string $url Direct URL to the attachment file (from wp-content). 4645 * @type int $width If the attachment is an image, represents the width of the image in pixels. 4646 * } 4647 */ 4648 function wp_prepare_attachment_for_js( $attachment ) { 4649 $attachment = get_post( $attachment ); 4650 4651 if ( ! $attachment ) { 4652 return null; 4653 } 4654 4655 if ( 'attachment' !== $attachment->post_type ) { 4656 return null; 4657 } 4658 4659 $meta = wp_get_attachment_metadata( $attachment->ID ); 4660 if ( str_contains( $attachment->post_mime_type, '/' ) ) { 4661 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type ); 4662 } else { 4663 list( $type, $subtype ) = array( $attachment->post_mime_type, '' ); 4664 } 4665 4666 $attachment_url = wp_get_attachment_url( $attachment->ID ); 4667 $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url ); 4668 4669 $response = array( 4670 'id' => $attachment->ID, 4671 'title' => $attachment->post_title, 4672 'filename' => wp_basename( get_attached_file( $attachment->ID ) ), 4673 'url' => esc_url_raw( $attachment_url ), 4674 'link' => get_attachment_link( $attachment->ID ), 4675 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ), 4676 'author' => $attachment->post_author, 4677 'description' => $attachment->post_content, 4678 'caption' => $attachment->post_excerpt, 4679 'name' => $attachment->post_name, 4680 'status' => $attachment->post_status, 4681 'uploadedTo' => $attachment->post_parent, 4682 'date' => strtotime( $attachment->post_date_gmt ) * 1000, 4683 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000, 4684 'menuOrder' => $attachment->menu_order, 4685 'mime' => $attachment->post_mime_type, 4686 'type' => $type, 4687 'subtype' => $subtype, 4688 'icon' => wp_mime_type_icon( $attachment->ID, '.svg' ), 4689 'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ), 4690 'nonces' => array( 4691 'update' => false, 4692 'delete' => false, 4693 'edit' => false, 4694 ), 4695 'editLink' => false, 4696 'meta' => false, 4697 ); 4698 4699 $author = new WP_User( $attachment->post_author ); 4700 4701 if ( $author->exists() ) { 4702 $author_name = $author->display_name ? $author->display_name : $author->nickname; 4703 $response['authorName'] = html_entity_decode( $author_name, ENT_QUOTES, get_bloginfo( 'charset' ) ); 4704 $response['authorLink'] = get_edit_user_link( $author->ID ); 4705 } else { 4706 $response['authorName'] = __( '(no author)' ); 4707 } 4708 4709 if ( $attachment->post_parent ) { 4710 $post_parent = get_post( $attachment->post_parent ); 4711 if ( $post_parent && current_user_can( 'read_post', $attachment->post_parent ) ) { 4712 $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' ); 4713 $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' ); 4714 } 4715 } 4716 4717 $attached_file = get_attached_file( $attachment->ID ); 4718 4719 if ( isset( $meta['filesize'] ) ) { 4720 $bytes = $meta['filesize']; 4721 } elseif ( file_exists( $attached_file ) ) { 4722 $bytes = wp_filesize( $attached_file ); 4723 } else { 4724 $bytes = ''; 4725 } 4726 4727 if ( $bytes ) { 4728 $response['filesizeInBytes'] = $bytes; 4729 $response['filesizeHumanReadable'] = size_format( $bytes ); 4730 } 4731 4732 $context = get_post_meta( $attachment->ID, '_wp_attachment_context', true ); 4733 $response['context'] = ( $context ) ? $context : ''; 4734 4735 if ( current_user_can( 'edit_post', $attachment->ID ) ) { 4736 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID ); 4737 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID ); 4738 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' ); 4739 } 4740 4741 if ( current_user_can( 'delete_post', $attachment->ID ) ) { 4742 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID ); 4743 } 4744 4745 if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) { 4746 $sizes = array(); 4747 4748 /** This filter is documented in wp-admin/includes/media.php */ 4749 $possible_sizes = apply_filters( 4750 'image_size_names_choose', 4751 array( 4752 'thumbnail' => __( 'Thumbnail' ), 4753 'medium' => __( 'Medium' ), 4754 'large' => __( 'Large' ), 4755 'full' => __( 'Full Size' ), 4756 ) 4757 ); 4758 unset( $possible_sizes['full'] ); 4759 4760 /* 4761 * Loop through all potential sizes that may be chosen. Try to do this with some efficiency. 4762 * First: run the image_downsize filter. If it returns something, we can use its data. 4763 * If the filter does not return something, then image_downsize() is just an expensive way 4764 * to check the image metadata, which we do second. 4765 */ 4766 foreach ( $possible_sizes as $size => $label ) { 4767 4768 /** This filter is documented in wp-includes/media.php */ 4769 $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ); 4770 4771 if ( $downsize ) { 4772 if ( empty( $downsize[3] ) ) { 4773 continue; 4774 } 4775 4776 $sizes[ $size ] = array( 4777 'height' => $downsize[2], 4778 'width' => $downsize[1], 4779 'url' => esc_url_raw( $downsize[0] ), 4780 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape', 4781 ); 4782 } elseif ( isset( $meta['sizes'][ $size ] ) ) { 4783 // Nothing from the filter, so consult image metadata if we have it. 4784 $size_meta = $meta['sizes'][ $size ]; 4785 4786 /* 4787 * We have the actual image size, but might need to further constrain it if content_width is narrower. 4788 * Thumbnail, medium, and full sizes are also checked against the site's height/width options. 4789 */ 4790 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' ); 4791 4792 $sizes[ $size ] = array( 4793 'height' => $height, 4794 'width' => $width, 4795 'url' => esc_url_raw( $base_url . $size_meta['file'] ), 4796 'orientation' => $height > $width ? 'portrait' : 'landscape', 4797 ); 4798 } 4799 } 4800 4801 if ( 'image' === $type ) { 4802 if ( ! empty( $meta['original_image'] ) ) { 4803 $original_image_url = wp_get_original_image_url( $attachment->ID ); 4804 $response['originalImageURL'] = $original_image_url ? esc_url_raw( $original_image_url ) : ''; 4805 $response['originalImageName'] = wp_basename( wp_get_original_image_path( $attachment->ID ) ); 4806 } 4807 4808 $sizes['full'] = array( 'url' => esc_url_raw( $attachment_url ) ); 4809 4810 if ( isset( $meta['height'], $meta['width'] ) ) { 4811 $sizes['full']['height'] = $meta['height']; 4812 $sizes['full']['width'] = $meta['width']; 4813 $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape'; 4814 } 4815 4816 $response = array_merge( $response, $sizes['full'] ); 4817 } elseif ( $meta['sizes']['full']['file'] ) { 4818 $sizes['full'] = array( 4819 'url' => esc_url_raw( $base_url . $meta['sizes']['full']['file'] ), 4820 'height' => $meta['sizes']['full']['height'], 4821 'width' => $meta['sizes']['full']['width'], 4822 'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape', 4823 ); 4824 } 4825 4826 $response = array_merge( $response, array( 'sizes' => $sizes ) ); 4827 } 4828 4829 if ( $meta && 'video' === $type ) { 4830 if ( isset( $meta['width'] ) ) { 4831 $response['width'] = (int) $meta['width']; 4832 } 4833 if ( isset( $meta['height'] ) ) { 4834 $response['height'] = (int) $meta['height']; 4835 } 4836 } 4837 4838 if ( $meta && ( 'audio' === $type || 'video' === $type ) ) { 4839 if ( isset( $meta['length_formatted'] ) ) { 4840 $response['fileLength'] = $meta['length_formatted']; 4841 $response['fileLengthHumanReadable'] = human_readable_duration( $meta['length_formatted'] ); 4842 } 4843 4844 $response['meta'] = array(); 4845 foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) { 4846 $response['meta'][ $key ] = false; 4847 4848 if ( ! empty( $meta[ $key ] ) ) { 4849 $response['meta'][ $key ] = $meta[ $key ]; 4850 } 4851 } 4852 4853 $id = get_post_thumbnail_id( $attachment->ID ); 4854 if ( ! empty( $id ) ) { 4855 $response_image_full = wp_get_attachment_image_src( $id, 'full' ); 4856 if ( is_array( $response_image_full ) ) { 4857 $response['image'] = array( 4858 'src' => esc_url_raw( $response_image_full[0] ), 4859 'width' => $response_image_full[1], 4860 'height' => $response_image_full[2], 4861 ); 4862 } 4863 4864 $response_image_thumb = wp_get_attachment_image_src( $id, 'thumbnail' ); 4865 if ( is_array( $response_image_thumb ) ) { 4866 $response['thumb'] = array( 4867 'src' => esc_url_raw( $response_image_thumb[0] ), 4868 'width' => $response_image_thumb[1], 4869 'height' => $response_image_thumb[2], 4870 ); 4871 } 4872 } else { 4873 $src = wp_mime_type_icon( $attachment->ID, '.svg' ); 4874 $width = 48; 4875 $height = 64; 4876 $response['image'] = compact( 'src', 'width', 'height' ); 4877 $response['thumb'] = compact( 'src', 'width', 'height' ); 4878 } 4879 } 4880 4881 if ( function_exists( 'get_compat_media_markup' ) ) { 4882 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) ); 4883 } 4884 4885 if ( function_exists( 'get_media_states' ) ) { 4886 $media_states = get_media_states( $attachment ); 4887 if ( ! empty( $media_states ) ) { 4888 $response['mediaStates'] = implode( ', ', $media_states ); 4889 } 4890 } 4891 4892 /** 4893 * Filters the attachment data prepared for JavaScript. 4894 * 4895 * @since 3.5.0 4896 * 4897 * @param array $response Array of prepared attachment data. See {@see wp_prepare_attachment_for_js()}. 4898 * @param WP_Post $attachment Attachment object. 4899 * @param array|false $meta Array of attachment meta data, or false if there is none. 4900 */ 4901 return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta ); 4902 } 4903 4904 /** 4905 * Enqueues all scripts, styles, settings, and templates necessary to use 4906 * all media JS APIs. 4907 * 4908 * @since 3.5.0 4909 * 4910 * @global int $content_width 4911 * @global wpdb $wpdb WordPress database abstraction object. 4912 * @global WP_Locale $wp_locale WordPress date and time locale object. 4913 * 4914 * @param array $args { 4915 * Arguments for enqueuing media scripts. 4916 * 4917 * @type int|WP_Post $post Post ID or post object. 4918 * } 4919 */ 4920 function wp_enqueue_media( $args = array() ) { 4921 // Enqueue me just once per page, please. 4922 if ( did_action( 'wp_enqueue_media' ) ) { 4923 return; 4924 } 4925 4926 global $content_width, $wpdb, $wp_locale; 4927 4928 $defaults = array( 4929 'post' => null, 4930 ); 4931 $args = wp_parse_args( $args, $defaults ); 4932 4933 /* 4934 * We're going to pass the old thickbox media tabs to `media_upload_tabs` 4935 * to ensure plugins will work. We will then unset those tabs. 4936 */ 4937 $tabs = array( 4938 // handler action suffix => tab label 4939 'type' => '', 4940 'type_url' => '', 4941 'gallery' => '', 4942 'library' => '', 4943 ); 4944 4945 /** This filter is documented in wp-admin/includes/media.php */ 4946 $tabs = apply_filters( 'media_upload_tabs', $tabs ); 4947 unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] ); 4948 4949 $props = array( 4950 'link' => get_option( 'image_default_link_type' ), // DB default is 'file'. 4951 'align' => get_option( 'image_default_align' ), // Empty default. 4952 'size' => get_option( 'image_default_size' ), // Empty default. 4953 ); 4954 4955 $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() ); 4956 $mimes = get_allowed_mime_types(); 4957 $ext_mimes = array(); 4958 foreach ( $exts as $ext ) { 4959 foreach ( $mimes as $ext_preg => $mime_match ) { 4960 if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) { 4961 $ext_mimes[ $ext ] = $mime_match; 4962 break; 4963 } 4964 } 4965 } 4966 4967 /** 4968 * Allows showing or hiding the "Create Audio Playlist" button in the media library. 4969 * 4970 * By default, the "Create Audio Playlist" button will always be shown in 4971 * the media library. If this filter returns `null`, a query will be run 4972 * to determine whether the media library contains any audio items. This 4973 * was the default behavior prior to version 4.8.0, but this query is 4974 * expensive for large media libraries. 4975 * 4976 * @since 4.7.4 4977 * @since 4.8.0 The filter's default value is `true` rather than `null`. 4978 * 4979 * @link https://core.trac.wordpress.org/ticket/31071 4980 * 4981 * @param bool|null $show Whether to show the button, or `null` to decide based 4982 * on whether any audio files exist in the media library. 4983 */ 4984 $show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true ); 4985 if ( null === $show_audio_playlist ) { 4986 $show_audio_playlist = $wpdb->get_var( 4987 "SELECT ID 4988 FROM $wpdb->posts 4989 WHERE post_type = 'attachment' 4990 AND post_mime_type LIKE 'audio%' 4991 LIMIT 1" 4992 ); 4993 } 4994 4995 /** 4996 * Allows showing or hiding the "Create Video Playlist" button in the media library. 4997 * 4998 * By default, the "Create Video Playlist" button will always be shown in 4999 * the media library. If this filter returns `null`, a query will be run 5000 * to determine whether the media library contains any video items. This 5001 * was the default behavior prior to version 4.8.0, but this query is 5002 * expensive for large media libraries. 5003 * 5004 * @since 4.7.4 5005 * @since 4.8.0 The filter's default value is `true` rather than `null`. 5006 * 5007 * @link https://core.trac.wordpress.org/ticket/31071 5008 * 5009 * @param bool|null $show Whether to show the button, or `null` to decide based 5010 * on whether any video files exist in the media library. 5011 */ 5012 $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true ); 5013 if ( null === $show_video_playlist ) { 5014 $show_video_playlist = $wpdb->get_var( 5015 "SELECT ID 5016 FROM $wpdb->posts 5017 WHERE post_type = 'attachment' 5018 AND post_mime_type LIKE 'video%' 5019 LIMIT 1" 5020 ); 5021 } 5022 5023 /** 5024 * Allows overriding the list of months displayed in the media library. 5025 * 5026 * By default (if this filter does not return an array), a query will be 5027 * run to determine the months that have media items. This query can be 5028 * expensive for large media libraries, so it may be desirable for sites to 5029 * override this behavior. 5030 * 5031 * @since 4.7.4 5032 * 5033 * @link https://core.trac.wordpress.org/ticket/31071 5034 * 5035 * @param stdClass[]|null $months An array of objects with `month` and `year` 5036 * properties, or `null` for default behavior. 5037 */ 5038 $months = apply_filters( 'media_library_months_with_files', null ); 5039 if ( ! is_array( $months ) ) { 5040 $months = $wpdb->get_results( 5041 $wpdb->prepare( 5042 "SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month 5043 FROM $wpdb->posts 5044 WHERE post_type = %s 5045 ORDER BY post_date DESC", 5046 'attachment' 5047 ) 5048 ); 5049 } 5050 foreach ( $months as $month_year ) { 5051 $month_year->text = sprintf( 5052 /* translators: 1: Month, 2: Year. */ 5053 __( '%1$s %2$d' ), 5054 $wp_locale->get_month( $month_year->month ), 5055 $month_year->year 5056 ); 5057 } 5058 5059 $infinite_scrolling = true; 5060 5061 // A user can opt out of infinite scrolling via their profile's personal options. 5062 if ( 'false' === get_user_option( 'infinite_scrolling' ) ) { 5063 $infinite_scrolling = false; 5064 } 5065 5066 /** 5067 * Filters whether the Media Library grid has infinite scrolling. Default `true`. 5068 * 5069 * This setting respects the current user's "Infinite Scrolling" personal 5070 * option, but a filter callback takes precedence over that preference. 5071 * 5072 * @since 5.8.0 5073 * @since 7.1.0 Changed default to `true` and introduced per-user opt-out of infinite scrolling. 5074 * 5075 * @param bool $infinite_scrolling Whether the Media Library grid has infinite scrolling. 5076 */ 5077 $infinite_scrolling = apply_filters( 'media_library_infinite_scrolling', $infinite_scrolling ); 5078 5079 $settings = array( 5080 'tabs' => $tabs, 5081 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url( 'media-upload.php' ) ), 5082 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ), 5083 /** This filter is documented in wp-admin/includes/media.php */ 5084 'captions' => ! apply_filters( 'disable_captions', '' ), 5085 'nonce' => array( 5086 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ), 5087 'setAttachmentThumbnail' => wp_create_nonce( 'set-attachment-thumbnail' ), 5088 ), 5089 'post' => array( 5090 'id' => 0, 5091 ), 5092 'defaultProps' => $props, 5093 'attachmentCounts' => array( 5094 'audio' => ( $show_audio_playlist ) ? 1 : 0, 5095 'video' => ( $show_video_playlist ) ? 1 : 0, 5096 ), 5097 'oEmbedProxyUrl' => rest_url( 'oembed/1.0/proxy' ), 5098 'embedExts' => $exts, 5099 'embedMimes' => $ext_mimes, 5100 'contentWidth' => $content_width, 5101 'months' => $months, 5102 'mediaTrash' => MEDIA_TRASH ? 1 : 0, 5103 'infiniteScrolling' => ( $infinite_scrolling ) ? 1 : 0, 5104 ); 5105 5106 $post = null; 5107 if ( isset( $args['post'] ) ) { 5108 $post = get_post( $args['post'] ); 5109 $settings['post'] = array( 5110 'id' => $post->ID, 5111 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ), 5112 ); 5113 5114 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' ); 5115 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) { 5116 if ( wp_attachment_is( 'audio', $post ) ) { 5117 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' ); 5118 } elseif ( wp_attachment_is( 'video', $post ) ) { 5119 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' ); 5120 } 5121 } 5122 5123 if ( $thumbnail_support ) { 5124 $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true ); 5125 $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1; 5126 } 5127 } 5128 5129 if ( $post ) { 5130 $post_type_object = get_post_type_object( $post->post_type ); 5131 } else { 5132 $post_type_object = get_post_type_object( 'post' ); 5133 } 5134 5135 $strings = array( 5136 // Generic. 5137 'mediaFrameDefaultTitle' => __( 'Media' ), 5138 'url' => __( 'URL' ), 5139 'addMedia' => __( 'Add media' ), 5140 'search' => __( 'Search' ), 5141 'select' => __( 'Select' ), 5142 'cancel' => __( 'Cancel' ), 5143 'update' => __( 'Update' ), 5144 'replace' => __( 'Replace' ), 5145 'remove' => __( 'Remove' ), 5146 'back' => __( 'Back' ), 5147 /* 5148 * translators: This is a would-be plural string used in the media manager. 5149 * If there is not a word you can use in your language to avoid issues with the 5150 * lack of plural support here, turn it into "selected: %d" then translate it. 5151 */ 5152 'selected' => __( '%d selected' ), 5153 'dragInfo' => __( 'Drag and drop to reorder media files.' ), 5154 5155 // Upload. 5156 'uploadFilesTitle' => __( 'Upload files' ), 5157 'uploadImagesTitle' => __( 'Upload images' ), 5158 5159 // Library. 5160 'mediaLibraryTitle' => __( 'Media Library' ), 5161 'insertMediaTitle' => __( 'Add media' ), 5162 'createNewGallery' => __( 'Create a new gallery' ), 5163 'createNewPlaylist' => __( 'Create a new playlist' ), 5164 'createNewVideoPlaylist' => __( 'Create a new video playlist' ), 5165 'returnToLibrary' => __( '← Go to library' ), 5166 'allMediaItems' => __( 'All media items' ), 5167 'allDates' => __( 'All dates' ), 5168 'noItemsFound' => __( 'No items found.' ), 5169 'insertIntoPost' => $post_type_object->labels->insert_into_item, 5170 'unattached' => _x( 'Unattached', 'media items' ), 5171 'mine' => _x( 'Mine', 'media items' ), 5172 'trash' => _x( 'Trash', 'noun' ), 5173 'uploadedToThisPost' => $post_type_object->labels->uploaded_to_this_item, 5174 'warnDelete' => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ), 5175 'warnBulkDelete' => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ), 5176 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ), 5177 'bulkSelect' => __( 'Bulk select' ), 5178 'trashSelected' => __( 'Move to Trash' ), 5179 'restoreSelected' => __( 'Restore from Trash' ), 5180 'deletePermanently' => __( 'Delete permanently' ), 5181 'errorDeleting' => __( 'Error in deleting the attachment.' ), 5182 'apply' => __( 'Apply' ), 5183 'filterByDate' => __( 'Filter by date' ), 5184 'filterByType' => __( 'Filter by type' ), 5185 'searchLabel' => __( 'Search media' ), 5186 'searchMediaLabel' => __( 'Search media' ), // Backward compatibility pre-5.3. 5187 'searchMediaPlaceholder' => __( 'Search media items...' ), // Placeholder (no ellipsis), backward compatibility pre-5.3. 5188 /* translators: %d: Number of attachments found in a search. */ 5189 'mediaFound' => __( 'Number of media items found: %d' ), 5190 'noMedia' => __( 'No media items found.' ), 5191 'noMediaTryNewSearch' => __( 'No media items found. Try a different search.' ), 5192 /* translators: %s: Media item title or file name. */ 5193 'mediaItemViewed' => __( 'Viewing media item: %s' ), 5194 5195 // Library Details. 5196 'attachmentDetails' => __( 'Attachment details' ), 5197 5198 // From URL. 5199 'insertFromUrlTitle' => __( 'Insert from URL' ), 5200 5201 // Featured Images. 5202 'setFeaturedImageTitle' => $post_type_object->labels->featured_image, 5203 'setFeaturedImage' => $post_type_object->labels->set_featured_image, 5204 5205 // Gallery. 5206 'createGalleryTitle' => __( 'Create gallery' ), 5207 'editGalleryTitle' => __( 'Edit gallery' ), 5208 'cancelGalleryTitle' => __( '← Cancel gallery' ), 5209 'insertGallery' => __( 'Insert gallery' ), 5210 'updateGallery' => __( 'Update gallery' ), 5211 'addToGallery' => __( 'Add to gallery' ), 5212 'addToGalleryTitle' => __( 'Add to gallery' ), 5213 'reverseOrder' => __( 'Reverse order' ), 5214 5215 // Edit Image. 5216 'imageDetailsTitle' => __( 'Image details' ), 5217 'imageReplaceTitle' => __( 'Replace image' ), 5218 'imageDetailsCancel' => __( 'Cancel edit' ), 5219 'editImage' => __( 'Edit image' ), 5220 5221 // Crop Image. 5222 'chooseImage' => __( 'Choose image' ), 5223 'selectAndCrop' => __( 'Select and crop' ), 5224 'skipCropping' => __( 'Skip cropping' ), 5225 'cropImage' => __( 'Crop image' ), 5226 'cropYourImage' => __( 'Crop your image' ), 5227 'cropping' => __( 'Cropping…' ), 5228 /* translators: 1: Suggested width number, 2: Suggested height number. */ 5229 'suggestedDimensions' => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ), 5230 'cropError' => __( 'There has been an error cropping your image.' ), 5231 5232 // Edit Audio. 5233 'audioDetailsTitle' => __( 'Audio details' ), 5234 'audioReplaceTitle' => __( 'Replace audio' ), 5235 'audioAddSourceTitle' => __( 'Add audio source' ), 5236 'audioDetailsCancel' => __( 'Cancel edit' ), 5237 5238 // Edit Video. 5239 'videoDetailsTitle' => __( 'Video details' ), 5240 'videoReplaceTitle' => __( 'Replace video' ), 5241 'videoAddSourceTitle' => __( 'Add video source' ), 5242 'videoDetailsCancel' => __( 'Cancel edit' ), 5243 'videoSelectPosterImageTitle' => __( 'Select poster image' ), 5244 'videoAddTrackTitle' => __( 'Add subtitles' ), 5245 5246 // Playlist. 5247 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ), 5248 'createPlaylistTitle' => __( 'Create audio playlist' ), 5249 'editPlaylistTitle' => __( 'Edit audio playlist' ), 5250 'cancelPlaylistTitle' => __( '← Cancel audio playlist' ), 5251 'insertPlaylist' => __( 'Insert audio playlist' ), 5252 'updatePlaylist' => __( 'Update audio playlist' ), 5253 'addToPlaylist' => __( 'Add to audio playlist' ), 5254 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ), 5255 5256 // Video Playlist. 5257 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ), 5258 'createVideoPlaylistTitle' => __( 'Create video playlist' ), 5259 'editVideoPlaylistTitle' => __( 'Edit video playlist' ), 5260 'cancelVideoPlaylistTitle' => __( '← Cancel video playlist' ), 5261 'insertVideoPlaylist' => __( 'Insert video playlist' ), 5262 'updateVideoPlaylist' => __( 'Update video playlist' ), 5263 'addToVideoPlaylist' => __( 'Add to video playlist' ), 5264 'addToVideoPlaylistTitle' => __( 'Add to video Playlist' ), 5265 5266 // Headings. 5267 'filterAttachments' => __( 'Filter media' ), 5268 'attachmentsList' => __( 'Media list' ), 5269 ); 5270 5271 /** 5272 * Filters the media view settings. 5273 * 5274 * @since 3.5.0 5275 * 5276 * @param array $settings List of media view settings. 5277 * @param WP_Post $post Post object. 5278 */ 5279 $settings = apply_filters( 'media_view_settings', $settings, $post ); 5280 5281 /** 5282 * Filters the media view strings. 5283 * 5284 * @since 3.5.0 5285 * 5286 * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript. 5287 * @param WP_Post $post Post object. 5288 */ 5289 $strings = apply_filters( 'media_view_strings', $strings, $post ); 5290 5291 $strings['settings'] = $settings; 5292 5293 /* 5294 * Ensure we enqueue media-editor first, that way media-views 5295 * is registered internally before we try to localize it. See #24724. 5296 */ 5297 wp_enqueue_script( 'media-editor' ); 5298 wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings ); 5299 5300 wp_enqueue_script( 'media-audiovideo' ); 5301 wp_enqueue_style( 'media-views' ); 5302 if ( is_admin() ) { 5303 wp_enqueue_script( 'mce-view' ); 5304 wp_enqueue_script( 'image-edit' ); 5305 } 5306 wp_enqueue_style( 'imgareaselect' ); 5307 wp_plupload_default_settings(); 5308 5309 require_once ABSPATH . WPINC . '/media-template.php'; 5310 add_action( 'admin_footer', 'wp_print_media_templates' ); 5311 add_action( 'wp_footer', 'wp_print_media_templates' ); 5312 add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' ); 5313 5314 /** 5315 * Fires at the conclusion of wp_enqueue_media(). 5316 * 5317 * @since 3.5.0 5318 */ 5319 do_action( 'wp_enqueue_media' ); 5320 } 5321 5322 /** 5323 * Retrieves media attached to the passed post. 5324 * 5325 * @since 3.6.0 5326 * 5327 * @param string $type Mime type. 5328 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. 5329 * @return WP_Post[] Array of media attached to the given post. 5330 */ 5331 function get_attached_media( $type, $post = 0 ) { 5332 $post = get_post( $post ); 5333 5334 if ( ! $post ) { 5335 return array(); 5336 } 5337 5338 $args = array( 5339 'post_parent' => $post->ID, 5340 'post_type' => 'attachment', 5341 'post_mime_type' => $type, 5342 'posts_per_page' => -1, 5343 'orderby' => 'menu_order', 5344 'order' => 'ASC', 5345 ); 5346 5347 /** 5348 * Filters arguments used to retrieve media attached to the given post. 5349 * 5350 * @since 3.6.0 5351 * 5352 * @param array $args Post query arguments. 5353 * @param string $type Mime type of the desired media. 5354 * @param WP_Post $post Post object. 5355 */ 5356 $args = apply_filters( 'get_attached_media_args', $args, $type, $post ); 5357 5358 $children = get_children( $args ); 5359 5360 /** 5361 * Filters the list of media attached to the given post. 5362 * 5363 * @since 3.6.0 5364 * 5365 * @param WP_Post[] $children Array of media attached to the given post. 5366 * @param string $type Mime type of the media desired. 5367 * @param WP_Post $post Post object. 5368 */ 5369 return (array) apply_filters( 'get_attached_media', $children, $type, $post ); 5370 } 5371 5372 /** 5373 * Checks the HTML content for an audio, video, object, embed, or iframe tags. 5374 * 5375 * @since 3.6.0 5376 * 5377 * @param string $content A string of HTML which might contain media elements. 5378 * @param string[] $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'. 5379 * @return string[] Array of found HTML media elements. 5380 */ 5381 function get_media_embedded_in_content( $content, $types = null ) { 5382 $html = array(); 5383 5384 /** 5385 * Filters the embedded media types that are allowed to be returned from the content blob. 5386 * 5387 * @since 4.2.0 5388 * 5389 * @param string[] $allowed_media_types An array of allowed media types. Default media types are 5390 * 'audio', 'video', 'object', 'embed', and 'iframe'. 5391 */ 5392 $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) ); 5393 5394 if ( ! empty( $types ) ) { 5395 if ( ! is_array( $types ) ) { 5396 $types = array( $types ); 5397 } 5398 5399 $allowed_media_types = array_intersect( $allowed_media_types, $types ); 5400 } 5401 5402 $tags = implode( '|', $allowed_media_types ); 5403 5404 if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) { 5405 foreach ( $matches[0] as $match ) { 5406 $html[] = $match; 5407 } 5408 } 5409 5410 return $html; 5411 } 5412 5413 /** 5414 * Retrieves galleries from the passed post's content. 5415 * 5416 * @since 3.6.0 5417 * 5418 * @param int|WP_Post $post Post ID or object. 5419 * @param bool $html Optional. Whether to return HTML or data in the array. Default true. 5420 * @return array A list of arrays, each containing gallery data and srcs parsed 5421 * from the expanded shortcode. 5422 */ 5423 function get_post_galleries( $post, $html = true ) { 5424 $post = get_post( $post ); 5425 5426 if ( ! $post ) { 5427 return array(); 5428 } 5429 5430 if ( ! has_shortcode( $post->post_content, 'gallery' ) && ! has_block( 'gallery', $post->post_content ) ) { 5431 return array(); 5432 } 5433 5434 $galleries = array(); 5435 if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) { 5436 foreach ( $matches as $shortcode ) { 5437 if ( 'gallery' === $shortcode[2] ) { 5438 $srcs = array(); 5439 5440 $shortcode_attrs = shortcode_parse_atts( $shortcode[3] ); 5441 5442 // Specify the post ID of the gallery we're viewing if the shortcode doesn't reference another post already. 5443 if ( ! isset( $shortcode_attrs['id'] ) ) { 5444 $shortcode[3] .= ' id="' . (int) $post->ID . '"'; 5445 } 5446 5447 $gallery = do_shortcode_tag( $shortcode ); 5448 if ( $html ) { 5449 $galleries[] = $gallery; 5450 } else { 5451 preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER ); 5452 if ( ! empty( $src ) ) { 5453 foreach ( $src as $s ) { 5454 $srcs[] = $s[2]; 5455 } 5456 } 5457 5458 $galleries[] = array_merge( 5459 $shortcode_attrs, 5460 array( 5461 'src' => array_values( array_unique( $srcs ) ), 5462 ) 5463 ); 5464 } 5465 } 5466 } 5467 } 5468 5469 if ( has_block( 'gallery', $post->post_content ) ) { 5470 $post_blocks = parse_blocks( $post->post_content ); 5471 5472 while ( $block = array_shift( $post_blocks ) ) { 5473 $has_inner_blocks = ! empty( $block['innerBlocks'] ); 5474 5475 // Skip blocks with no blockName and no innerHTML. 5476 if ( ! $block['blockName'] ) { 5477 continue; 5478 } 5479 5480 // Skip non-Gallery blocks. 5481 if ( 'core/gallery' !== $block['blockName'] ) { 5482 // Move inner blocks into the root array before skipping. 5483 if ( $has_inner_blocks ) { 5484 array_push( $post_blocks, ...$block['innerBlocks'] ); 5485 } 5486 continue; 5487 } 5488 5489 // New Gallery block format as HTML. 5490 if ( $has_inner_blocks && $html ) { 5491 $block_html = wp_list_pluck( $block['innerBlocks'], 'innerHTML' ); 5492 $galleries[] = '<figure>' . implode( ' ', $block_html ) . '</figure>'; 5493 continue; 5494 } 5495 5496 $srcs = array(); 5497 5498 // New Gallery block format as an array. 5499 if ( $has_inner_blocks ) { 5500 $attrs = wp_list_pluck( $block['innerBlocks'], 'attrs' ); 5501 $ids = wp_list_pluck( $attrs, 'id' ); 5502 5503 foreach ( $ids as $id ) { 5504 $url = wp_get_attachment_url( $id ); 5505 5506 if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) { 5507 $srcs[] = $url; 5508 } 5509 } 5510 5511 $galleries[] = array( 5512 'ids' => implode( ',', $ids ), 5513 'src' => $srcs, 5514 ); 5515 5516 continue; 5517 } 5518 5519 // Old Gallery block format as HTML. 5520 if ( $html ) { 5521 $galleries[] = $block['innerHTML']; 5522 continue; 5523 } 5524 5525 // Old Gallery block format as an array. 5526 $ids = ! empty( $block['attrs']['ids'] ) ? $block['attrs']['ids'] : array(); 5527 5528 // If present, use the image IDs from the JSON blob as canonical. 5529 if ( ! empty( $ids ) ) { 5530 foreach ( $ids as $id ) { 5531 $url = wp_get_attachment_url( $id ); 5532 5533 if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) { 5534 $srcs[] = $url; 5535 } 5536 } 5537 5538 $galleries[] = array( 5539 'ids' => implode( ',', $ids ), 5540 'src' => $srcs, 5541 ); 5542 5543 continue; 5544 } 5545 5546 // Otherwise, extract srcs from the innerHTML. 5547 preg_match_all( '#src=([\'"])(.+?)\1#is', $block['innerHTML'], $found_srcs, PREG_SET_ORDER ); 5548 5549 if ( ! empty( $found_srcs[0] ) ) { 5550 foreach ( $found_srcs as $src ) { 5551 if ( isset( $src[2] ) && ! in_array( $src[2], $srcs, true ) ) { 5552 $srcs[] = $src[2]; 5553 } 5554 } 5555 } 5556 5557 $galleries[] = array( 'src' => $srcs ); 5558 } 5559 } 5560 5561 /** 5562 * Filters the list of all found galleries in the given post. 5563 * 5564 * @since 3.6.0 5565 * 5566 * @param array $galleries Associative array of all found post galleries. 5567 * @param WP_Post $post Post object. 5568 */ 5569 return apply_filters( 'get_post_galleries', $galleries, $post ); 5570 } 5571 5572 /** 5573 * Checks a specified post's content for gallery and, if present, return the first 5574 * 5575 * @since 3.6.0 5576 * 5577 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. 5578 * @param bool $html Optional. Whether to return HTML or data. Default is true. 5579 * @return string|array Gallery data and srcs parsed from the expanded shortcode. 5580 */ 5581 function get_post_gallery( $post = 0, $html = true ) { 5582 $galleries = get_post_galleries( $post, $html ); 5583 $gallery = reset( $galleries ); 5584 5585 /** 5586 * Filters the first-found post gallery. 5587 * 5588 * @since 3.6.0 5589 * 5590 * @param array $gallery The first-found post gallery. 5591 * @param int|WP_Post $post Post ID or object. 5592 * @param array $galleries Associative array of all found post galleries. 5593 */ 5594 return apply_filters( 'get_post_gallery', $gallery, $post, $galleries ); 5595 } 5596 5597 /** 5598 * Retrieves the image srcs from galleries from a post's content, if present. 5599 * 5600 * @since 3.6.0 5601 * 5602 * @see get_post_galleries() 5603 * 5604 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`. 5605 * @return array A list of lists, each containing image srcs parsed. 5606 * from an expanded shortcode 5607 */ 5608 function get_post_galleries_images( $post = 0 ) { 5609 $galleries = get_post_galleries( $post, false ); 5610 return wp_list_pluck( $galleries, 'src' ); 5611 } 5612 5613 /** 5614 * Checks a post's content for galleries and return the image srcs for the first found gallery. 5615 * 5616 * @since 3.6.0 5617 * 5618 * @see get_post_gallery() 5619 * 5620 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`. 5621 * @return string[] A list of a gallery's image srcs in order. 5622 */ 5623 function get_post_gallery_images( $post = 0 ) { 5624 $gallery = get_post_gallery( $post, false ); 5625 return empty( $gallery['src'] ) ? array() : $gallery['src']; 5626 } 5627 5628 /** 5629 * Maybe attempts to generate attachment metadata, if missing. 5630 * 5631 * @since 3.9.0 5632 * 5633 * @param WP_Post $attachment Attachment object. 5634 */ 5635 function wp_maybe_generate_attachment_metadata( $attachment ) { 5636 if ( empty( $attachment ) || empty( $attachment->ID ) ) { 5637 return; 5638 } 5639 5640 $attachment_id = (int) $attachment->ID; 5641 $file = get_attached_file( $attachment_id ); 5642 $meta = wp_get_attachment_metadata( $attachment_id ); 5643 5644 if ( empty( $meta ) && file_exists( $file ) ) { 5645 $_meta = get_post_meta( $attachment_id ); 5646 $_lock = 'wp_generating_att_' . $attachment_id; 5647 5648 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $_lock ) ) { 5649 set_transient( $_lock, $file ); 5650 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) ); 5651 delete_transient( $_lock ); 5652 } 5653 } 5654 } 5655 5656 /** 5657 * Tries to convert an attachment URL into a post ID. 5658 * 5659 * @since 4.0.0 5660 * 5661 * @global wpdb $wpdb WordPress database abstraction object. 5662 * 5663 * @param string $url The URL to resolve. 5664 * @return int The found post ID, or 0 on failure. 5665 */ 5666 function attachment_url_to_postid( $url ) { 5667 global $wpdb; 5668 5669 /** 5670 * Filters the attachment ID to allow short-circuit the function. 5671 * 5672 * Allows plugins to short-circuit attachment ID lookups. Plugins making 5673 * use of this function should return: 5674 * 5675 * - 0 (integer) to indicate the attachment is not found, 5676 * - attachment ID (integer) to indicate the attachment ID found, 5677 * - null to indicate WordPress should proceed with the lookup. 5678 * 5679 * Warning: The post ID may be null or zero, both of which cast to a 5680 * boolean false. For information about casting to booleans see the 5681 * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}. 5682 * Use the === operator for testing the post ID when developing filters using 5683 * this hook. 5684 * 5685 * @since 6.7.0 5686 * 5687 * @param int|null $post_id The result of the post ID lookup. Null to indicate 5688 * no lookup has been attempted. Default null. 5689 * @param string $url The URL being looked up. 5690 */ 5691 $post_id = apply_filters( 'pre_attachment_url_to_postid', null, $url ); 5692 if ( null !== $post_id ) { 5693 return (int) $post_id; 5694 } 5695 5696 $dir = wp_get_upload_dir(); 5697 $path = $url; 5698 5699 $site_url = parse_url( $dir['url'] ); 5700 $image_path = parse_url( $path ); 5701 5702 // Force the protocols to match if needed. 5703 if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) { 5704 $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path ); 5705 } 5706 5707 if ( str_starts_with( $path, $dir['baseurl'] . '/' ) ) { 5708 $path = substr( $path, strlen( $dir['baseurl'] . '/' ) ); 5709 } 5710 5711 $sql = $wpdb->prepare( 5712 "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s", 5713 $path 5714 ); 5715 5716 $results = $wpdb->get_results( $sql ); 5717 $post_id = null; 5718 5719 if ( $results ) { 5720 // Use the first available result, but prefer a case-sensitive match, if exists. 5721 $post_id = reset( $results )->post_id; 5722 5723 if ( count( $results ) > 1 ) { 5724 foreach ( $results as $result ) { 5725 if ( $path === $result->meta_value ) { 5726 $post_id = $result->post_id; 5727 break; 5728 } 5729 } 5730 } 5731 } 5732 5733 /** 5734 * Filters an attachment ID found by URL. 5735 * 5736 * @since 4.2.0 5737 * 5738 * @param int|null $post_id The post_id (if any) found by the function. 5739 * @param string $url The URL being looked up. 5740 */ 5741 return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url ); 5742 } 5743 5744 /** 5745 * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view. 5746 * 5747 * @since 4.0.0 5748 * 5749 * @return string[] The relevant CSS file URLs. 5750 */ 5751 function wpview_media_sandbox_styles() { 5752 $version = 'ver=' . get_bloginfo( 'version' ); 5753 $mediaelement = includes_url( "js/mediaelement/mediaelementplayer-legacy.min.css?$version" ); 5754 $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" ); 5755 5756 return array( $mediaelement, $wpmediaelement ); 5757 } 5758 5759 /** 5760 * Registers the personal data exporter for media. 5761 * 5762 * @since 4.9.6 5763 * 5764 * @param array[] $exporters An array of personal data exporters, keyed by their ID. 5765 * @return array[] Updated array of personal data exporters. 5766 */ 5767 function wp_register_media_personal_data_exporter( $exporters ) { 5768 $exporters['wordpress-media'] = array( 5769 'exporter_friendly_name' => __( 'WordPress Media' ), 5770 'callback' => 'wp_media_personal_data_exporter', 5771 ); 5772 5773 return $exporters; 5774 } 5775 5776 /** 5777 * Finds and exports attachments associated with an email address. 5778 * 5779 * @since 4.9.6 5780 * 5781 * @param string $email_address The attachment owner email address. 5782 * @param int $page Attachment page number. 5783 * @return array { 5784 * An array of personal data. 5785 * 5786 * @type array[] $data An array of personal data arrays. 5787 * @type bool $done Whether the exporter is finished. 5788 * } 5789 */ 5790 function wp_media_personal_data_exporter( $email_address, $page = 1 ) { 5791 // Limit us to 50 attachments at a time to avoid timing out. 5792 $number = 50; 5793 $page = (int) $page; 5794 5795 $data_to_export = array(); 5796 5797 $user = get_user_by( 'email', $email_address ); 5798 if ( false === $user ) { 5799 return array( 5800 'data' => $data_to_export, 5801 'done' => true, 5802 ); 5803 } 5804 5805 $post_query = new WP_Query( 5806 array( 5807 'author' => $user->ID, 5808 'posts_per_page' => $number, 5809 'paged' => $page, 5810 'post_type' => 'attachment', 5811 'post_status' => 'any', 5812 'orderby' => 'ID', 5813 'order' => 'ASC', 5814 ) 5815 ); 5816 5817 foreach ( (array) $post_query->posts as $post ) { 5818 $attachment_url = wp_get_attachment_url( $post->ID ); 5819 5820 if ( $attachment_url ) { 5821 $post_data_to_export = array( 5822 array( 5823 'name' => __( 'URL' ), 5824 'value' => $attachment_url, 5825 ), 5826 ); 5827 5828 $data_to_export[] = array( 5829 'group_id' => 'media', 5830 'group_label' => __( 'Media' ), 5831 'group_description' => __( 'User’s media data.' ), 5832 'item_id' => "post-{$post->ID}", 5833 'data' => $post_data_to_export, 5834 ); 5835 } 5836 } 5837 5838 $done = $post_query->max_num_pages <= $page; 5839 5840 return array( 5841 'data' => $data_to_export, 5842 'done' => $done, 5843 ); 5844 } 5845 5846 /** 5847 * Adds additional default image sub-sizes. 5848 * 5849 * These sizes are meant to enhance the way WordPress displays images on the front-end on larger, 5850 * high-density devices. They make it possible to generate more suitable `srcset` and `sizes` attributes 5851 * when the users upload large images. 5852 * 5853 * The sizes can be changed or removed by themes and plugins but that is not recommended. 5854 * The size "names" reflect the image dimensions, so changing the sizes would be quite misleading. 5855 * 5856 * @since 5.3.0 5857 * @access private 5858 */ 5859 function _wp_add_additional_image_sizes() { 5860 // 2x medium_large size. 5861 add_image_size( '1536x1536', 1536, 1536 ); 5862 // 2x large size. 5863 add_image_size( '2048x2048', 2048, 2048 ); 5864 } 5865 5866 /** 5867 * Callback to enable showing of the user error when uploading .heic images. 5868 * 5869 * @since 5.5.0 5870 * @since 6.7.0 The default behavior is to enable heic uploads as long as the server 5871 * supports the format. The uploads are converted to JPEG's by default. 5872 * 5873 * @param array[] $plupload_settings The settings for Plupload.js. 5874 * @return array[] Modified settings for Plupload.js. 5875 */ 5876 function wp_show_heic_upload_error( $plupload_settings ) { 5877 // Check if HEIC images can be edited. 5878 if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/heic' ) ) ) { 5879 $plupload_init['heic_upload_error'] = true; 5880 } 5881 return $plupload_settings; 5882 } 5883 5884 /** 5885 * Allows PHP's getimagesize() to be debuggable when necessary. 5886 * 5887 * @since 5.7.0 5888 * @since 5.8.0 Added support for WebP images. 5889 * @since 6.5.0 Added support for AVIF images. 5890 * 5891 * @param string $filename The file path. 5892 * @param array $image_info Optional. Extended image information (passed by reference). 5893 * @return array|false Array of image information or false on failure. 5894 * @phpstan-return array{ 0: int, 1: int, 2: int, 3: string, mime: string, bits?: int, channels?: int }|false 5895 */ 5896 function wp_getimagesize( $filename, ?array &$image_info = null ) { 5897 // Don't silence errors when in debug mode, unless running unit tests. 5898 if ( defined( 'WP_DEBUG' ) && WP_DEBUG && ! defined( 'WP_RUN_CORE_TESTS' ) ) { 5899 if ( 2 === func_num_args() ) { 5900 $info = getimagesize( $filename, $image_info ); 5901 } else { 5902 $info = getimagesize( $filename ); 5903 } 5904 } else { 5905 /* 5906 * Silencing notice and warning is intentional. 5907 * 5908 * getimagesize() has a tendency to generate errors, such as 5909 * "corrupt JPEG data: 7191 extraneous bytes before marker", 5910 * even when it's able to provide image size information. 5911 * 5912 * See https://core.trac.wordpress.org/ticket/42480 5913 */ 5914 if ( 2 === func_num_args() ) { 5915 $info = @getimagesize( $filename, $image_info ); 5916 } else { 5917 $info = @getimagesize( $filename ); 5918 } 5919 } 5920 5921 if ( 5922 ! empty( $info ) && 5923 // Some PHP versions return 0x0 sizes from `getimagesize` for unrecognized image formats, including AVIFs. 5924 ! ( empty( $info[0] ) && empty( $info[1] ) ) 5925 ) { 5926 return $info; 5927 } 5928 5929 $image_mime_type = wp_get_image_mime( $filename ); 5930 5931 // Not an image? 5932 if ( false === $image_mime_type ) { 5933 return false; 5934 } 5935 5936 /* 5937 * For PHP versions that don't support WebP images, 5938 * extract the image size info from the file headers. 5939 */ 5940 if ( 'image/webp' === $image_mime_type ) { 5941 $webp_info = wp_get_webp_info( $filename ); 5942 $width = $webp_info['width']; 5943 $height = $webp_info['height']; 5944 5945 // Mimic the native return format. 5946 if ( $width && $height ) { 5947 return array( 5948 $width, 5949 $height, 5950 IMAGETYPE_WEBP, 5951 sprintf( 5952 'width="%d" height="%d"', 5953 $width, 5954 $height 5955 ), 5956 'mime' => 'image/webp', 5957 ); 5958 } 5959 } 5960 5961 // For PHP versions that don't support AVIF images, extract the image size info from the file headers. 5962 if ( 'image/avif' === $image_mime_type ) { 5963 $avif_info = wp_get_avif_info( $filename ); 5964 5965 $width = $avif_info['width']; 5966 $height = $avif_info['height']; 5967 5968 // Mimic the native return format. 5969 if ( $width && $height ) { 5970 return array( 5971 $width, 5972 $height, 5973 IMAGETYPE_AVIF, 5974 sprintf( 5975 'width="%d" height="%d"', 5976 $width, 5977 $height 5978 ), 5979 'mime' => 'image/avif', 5980 ); 5981 } 5982 } 5983 5984 // For PHP versions that don't support HEIC images, extract the size info using Imagick when available. 5985 if ( wp_is_heic_image_mime_type( $image_mime_type ) ) { 5986 $editor = wp_get_image_editor( $filename ); 5987 5988 if ( is_wp_error( $editor ) ) { 5989 return false; 5990 } 5991 5992 // If the editor for HEICs is Imagick, use it to get the image size. 5993 if ( $editor instanceof WP_Image_Editor_Imagick ) { 5994 $size = $editor->get_size(); 5995 return array( 5996 $size['width'], 5997 $size['height'], 5998 IMAGETYPE_HEIF, 5999 sprintf( 6000 'width="%d" height="%d"', 6001 $size['width'], 6002 $size['height'] 6003 ), 6004 'mime' => 'image/heic', 6005 ); 6006 } 6007 } 6008 6009 // The image could not be parsed. 6010 return false; 6011 } 6012 6013 /** 6014 * Extracts meta information about an AVIF file: width, height, bit depth, and number of channels. 6015 * 6016 * @since 6.5.0 6017 * 6018 * @param string $filename Path to an AVIF file. 6019 * @return array { 6020 * An array of AVIF image information. 6021 * 6022 * @type int|false $width Image width on success, false on failure. 6023 * @type int|false $height Image height on success, false on failure. 6024 * @type int|false $bit_depth Image bit depth on success, false on failure. 6025 * @type int|false $num_channels Image number of channels on success, false on failure. 6026 * } 6027 */ 6028 function wp_get_avif_info( $filename ) { 6029 $results = array( 6030 'width' => false, 6031 'height' => false, 6032 'bit_depth' => false, 6033 'num_channels' => false, 6034 ); 6035 6036 if ( 'image/avif' !== wp_get_image_mime( $filename ) ) { 6037 return $results; 6038 } 6039 6040 // Parse the file using libavifinfo's PHP implementation. 6041 require_once ABSPATH . WPINC . '/class-avif-info.php'; 6042 6043 $handle = fopen( $filename, 'rb' ); 6044 if ( $handle ) { 6045 $parser = new Avifinfo\Parser( $handle ); 6046 $success = $parser->parse_ftyp() && $parser->parse_file(); 6047 fclose( $handle ); 6048 if ( $success ) { 6049 $results = $parser->features->primary_item_features; 6050 } 6051 } 6052 return $results; 6053 } 6054 6055 /** 6056 * Extracts meta information about a WebP file: width, height, and type. 6057 * 6058 * @since 5.8.0 6059 * 6060 * @param string $filename Path to a WebP file. 6061 * @return array { 6062 * An array of WebP image information. 6063 * 6064 * @type int|false $width Image width on success, false on failure. 6065 * @type int|false $height Image height on success, false on failure. 6066 * @type string|false $type The WebP type: one of 'lossy', 'lossless' or 'animated-alpha'. 6067 * False on failure. 6068 * } 6069 */ 6070 function wp_get_webp_info( $filename ) { 6071 $width = false; 6072 $height = false; 6073 $type = false; 6074 6075 if ( 'image/webp' !== wp_get_image_mime( $filename ) ) { 6076 return compact( 'width', 'height', 'type' ); 6077 } 6078 6079 $magic = file_get_contents( $filename, false, null, 0, 40 ); 6080 6081 if ( false === $magic ) { 6082 return compact( 'width', 'height', 'type' ); 6083 } 6084 6085 // Make sure we got enough bytes. 6086 if ( strlen( $magic ) < 40 ) { 6087 return compact( 'width', 'height', 'type' ); 6088 } 6089 6090 /* 6091 * The headers are a little different for each of the three formats. 6092 * Header values based on WebP docs, see https://developers.google.com/speed/webp/docs/riff_container. 6093 */ 6094 switch ( substr( $magic, 12, 4 ) ) { 6095 // Lossy WebP. 6096 case 'VP8 ': 6097 $parts = unpack( 'v2', substr( $magic, 26, 4 ) ); 6098 $width = (int) ( $parts[1] & 0x3FFF ); 6099 $height = (int) ( $parts[2] & 0x3FFF ); 6100 $type = 'lossy'; 6101 break; 6102 // Lossless WebP. 6103 case 'VP8L': 6104 $parts = unpack( 'C4', substr( $magic, 21, 4 ) ); 6105 $width = (int) ( $parts[1] | ( ( $parts[2] & 0x3F ) << 8 ) ) + 1; 6106 $height = (int) ( ( ( $parts[2] & 0xC0 ) >> 6 ) | ( $parts[3] << 2 ) | ( ( $parts[4] & 0x03 ) << 10 ) ) + 1; 6107 $type = 'lossless'; 6108 break; 6109 // Animated/alpha WebP. 6110 case 'VP8X': 6111 // Pad 24-bit int. 6112 $width = unpack( 'V', substr( $magic, 24, 3 ) . "\x00" ); 6113 $width = (int) ( $width[1] & 0xFFFFFF ) + 1; 6114 // Pad 24-bit int. 6115 $height = unpack( 'V', substr( $magic, 27, 3 ) . "\x00" ); 6116 $height = (int) ( $height[1] & 0xFFFFFF ) + 1; 6117 $type = 'animated-alpha'; 6118 break; 6119 } 6120 6121 return compact( 'width', 'height', 'type' ); 6122 } 6123 6124 /** 6125 * Gets loading optimization attributes. 6126 * 6127 * This function returns an array of attributes that should be merged into the given attributes array to optimize 6128 * loading performance. Potential attributes returned by this function are: 6129 * - `loading` attribute with a value of "lazy" 6130 * - `fetchpriority` attribute with a value of "high" 6131 * - `decoding` attribute with a value of "async" 6132 * 6133 * If any of these attributes are already present in the given attributes, they will not be modified. Note that no 6134 * element should have both `loading="lazy"` and `fetchpriority="high"`, so the function will trigger a warning in case 6135 * both attributes are present with those values. 6136 * 6137 * @since 6.3.0 6138 * @since 7.0.0 Support `fetchpriority=low` and `fetchpriority=auto` so that `loading=lazy` is not added and the media count is not increased. 6139 * 6140 * @global WP_Query $wp_query WordPress Query object. 6141 * 6142 * @param string $tag_name The tag name. 6143 * @param array $attr Array of the attributes for the tag. 6144 * @param string $context Context for the element for which the loading optimization attribute is requested. 6145 * @return array Loading optimization attributes. 6146 */ 6147 function wp_get_loading_optimization_attributes( $tag_name, $attr, $context ) { 6148 global $wp_query; 6149 6150 /** 6151 * Filters whether to short-circuit loading optimization attributes. 6152 * 6153 * Returning an array from the filter will effectively short-circuit the loading of optimization attributes, 6154 * returning that value instead. 6155 * 6156 * @since 6.4.0 6157 * 6158 * @param array|false $loading_attrs False by default, or array of loading optimization attributes to short-circuit. 6159 * @param string $tag_name The tag name. 6160 * @param array $attr Array of the attributes for the tag. 6161 * @param string $context Context for the element for which the loading optimization attribute is requested. 6162 */ 6163 $loading_attrs = apply_filters( 'pre_wp_get_loading_optimization_attributes', false, $tag_name, $attr, $context ); 6164 6165 if ( is_array( $loading_attrs ) ) { 6166 return $loading_attrs; 6167 } 6168 6169 $loading_attrs = array(); 6170 6171 /* 6172 * Skip lazy-loading for the overall block template, as it is handled more granularly. 6173 * The skip is also applicable for `fetchpriority`. 6174 */ 6175 if ( 'template' === $context ) { 6176 /** This filter is documented in wp-includes/media.php */ 6177 return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context ); 6178 } 6179 6180 // For now this function only supports images and iframes. 6181 if ( 'img' !== $tag_name && 'iframe' !== $tag_name ) { 6182 /** This filter is documented in wp-includes/media.php */ 6183 return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context ); 6184 } 6185 6186 /* 6187 * Skip programmatically created images within content blobs as they need to be handled together with the other 6188 * images within the post content or widget content. 6189 * Without this clause, they would already be considered within their own context which skews the image count and 6190 * can result in the first post content image being lazy-loaded or an image further down the page being marked as a 6191 * high priority. 6192 */ 6193 if ( 6194 'the_content' !== $context && doing_filter( 'the_content' ) || 6195 'widget_text_content' !== $context && doing_filter( 'widget_text_content' ) || 6196 'widget_block_content' !== $context && doing_filter( 'widget_block_content' ) 6197 ) { 6198 /** This filter is documented in wp-includes/media.php */ 6199 return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context ); 6200 6201 } 6202 6203 /* 6204 * Add `decoding` with a value of "async" for every image unless it has a 6205 * conflicting `decoding` attribute already present. 6206 */ 6207 if ( 'img' === $tag_name ) { 6208 $loading_attrs['decoding'] = $attr['decoding'] ?? 'async'; 6209 } 6210 6211 // For any resources, width and height must be provided, to avoid layout shifts. 6212 if ( ! isset( $attr['width'], $attr['height'] ) ) { 6213 /** This filter is documented in wp-includes/media.php */ 6214 return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context ); 6215 } 6216 6217 /* 6218 * The key function logic starts here. 6219 */ 6220 $maybe_in_viewport = null; 6221 $increase_count = false; 6222 $maybe_increase_count = false; 6223 6224 // Logic to handle a `loading` attribute that is already provided. 6225 if ( isset( $attr['loading'] ) ) { 6226 /* 6227 * Interpret "lazy" as not in viewport. Any other value can be 6228 * interpreted as in viewport (realistically only "eager" or `false` 6229 * to force-omit the attribute are other potential values). 6230 */ 6231 if ( 'lazy' === $attr['loading'] ) { 6232 $maybe_in_viewport = false; 6233 } else { 6234 $maybe_in_viewport = true; 6235 } 6236 } 6237 6238 // Logic to handle a `fetchpriority` attribute that is already provided. 6239 $existing_fetchpriority = ( $attr['fetchpriority'] ?? null ); 6240 $is_low_fetchpriority = ( 'low' === $existing_fetchpriority ); 6241 if ( 'high' === $existing_fetchpriority ) { 6242 /* 6243 * If the image was already determined to not be in the viewport (e.g. 6244 * from an already provided `loading` attribute), trigger a warning. 6245 * Otherwise, the value can be interpreted as in viewport, since only 6246 * the most important in-viewport image should have `fetchpriority` set 6247 * to "high". 6248 */ 6249 if ( false === $maybe_in_viewport ) { 6250 _doing_it_wrong( 6251 __FUNCTION__, 6252 __( 'An image should not be lazy-loaded and marked as high priority at the same time.' ), 6253 '6.3.0' 6254 ); 6255 /* 6256 * Set `fetchpriority` here for backward-compatibility as we should 6257 * not override what a developer decided, even though it seems 6258 * incorrect. 6259 */ 6260 $loading_attrs['fetchpriority'] = 'high'; 6261 } else { 6262 $maybe_in_viewport = true; 6263 } 6264 } elseif ( $is_low_fetchpriority ) { 6265 /* 6266 * An IMG with fetchpriority=low is not initially displayed; it may be hidden in the Navigation Overlay, 6267 * or it may be occluded in a non-initial carousel slide. Such images must not be lazy-loaded because the browser 6268 * has no heuristic to know when to start loading them before the user needs to see them. 6269 */ 6270 $maybe_in_viewport = false; 6271 6272 // Preserve fetchpriority=low. 6273 $loading_attrs['fetchpriority'] = 'low'; 6274 } elseif ( 'auto' === $existing_fetchpriority ) { 6275 /* 6276 * When a block's visibility support identifies that the block is conditionally displayed based on the viewport 6277 * size, then it adds `fetchpriority=auto` to the block's IMG tags. These images must not be fetched with high 6278 * priority because they could be erroneously loaded in viewports which do not even display them. Contrarily, 6279 * they must not get `fetchpriority=low` because they may in fact be displayed in the current viewport. So as 6280 * a signal to indicate that an IMG may be in the viewport, `fetchpriority=auto` is added. This has the effect 6281 * here of preventing the media count from being increased, so that images hidden with block visibility do not 6282 * affect whether a following IMG gets `loading=lazy`. In particular, `loading=lazy` should still be omitted 6283 * on an IMG following any number of initial IMGs with `fetchpriority=auto` since those initial images may not 6284 * be displayed. 6285 */ 6286 6287 // Preserve fetchpriority=auto. 6288 $loading_attrs['fetchpriority'] = 'auto'; 6289 } 6290 6291 if ( null === $maybe_in_viewport ) { 6292 $header_enforced_contexts = array( 6293 'template_part_' . WP_TEMPLATE_PART_AREA_HEADER => true, 6294 'get_header_image_tag' => true, 6295 ); 6296 6297 /** 6298 * Filters the header-specific contexts. 6299 * 6300 * @since 6.4.0 6301 * 6302 * @param array $default_header_enforced_contexts Map of contexts for which elements should be considered 6303 * in the header of the page, as $context => $enabled 6304 * pairs. The $enabled should always be true. 6305 */ 6306 $header_enforced_contexts = apply_filters( 'wp_loading_optimization_force_header_contexts', $header_enforced_contexts ); 6307 6308 // Consider elements with these header-specific contexts to be in viewport. 6309 if ( isset( $header_enforced_contexts[ $context ] ) ) { 6310 $maybe_in_viewport = true; 6311 $maybe_increase_count = true; 6312 } elseif ( ! is_admin() && in_the_loop() && is_main_query() ) { 6313 /* 6314 * Get the content media count, since this is a main query 6315 * content element. This is accomplished by "increasing" 6316 * the count by zero, as the only way to get the count is 6317 * to call this function. 6318 * The actual count increase happens further below, based 6319 * on the `$increase_count` flag set here. 6320 */ 6321 $content_media_count = wp_increase_content_media_count( 0 ); 6322 $increase_count = true; 6323 6324 // If the count so far is below the threshold, `loading` attribute is omitted. 6325 if ( $content_media_count < wp_omit_loading_attr_threshold() ) { 6326 $maybe_in_viewport = true; 6327 } else { 6328 $maybe_in_viewport = false; 6329 } 6330 } elseif ( 6331 // Only apply for main query but before the loop. 6332 $wp_query->before_loop && $wp_query->is_main_query() 6333 /* 6334 * Any image before the loop, but after the header has started should not be lazy-loaded, 6335 * except when the footer has already started which can happen when the current template 6336 * does not include any loop. 6337 */ 6338 && did_action( 'get_header' ) && ! did_action( 'get_footer' ) 6339 ) { 6340 $maybe_in_viewport = true; 6341 $maybe_increase_count = true; 6342 } 6343 } 6344 6345 /* 6346 * If the element is in the viewport (`true`), potentially add 6347 * `fetchpriority` with a value of "high". Otherwise, i.e. if the element 6348 * is not in the viewport (`false`) or it is unknown (`null`), add 6349 * `loading` with a value of "lazy" if the element is not already being 6350 * de-prioritized with `fetchpriority=low` due to occlusion in 6351 * Navigation Overlay, non-initial carousel slides, or a collapsed Details block. 6352 */ 6353 if ( $maybe_in_viewport ) { 6354 $loading_attrs = wp_maybe_add_fetchpriority_high_attr( $loading_attrs, $tag_name, $attr ); 6355 } elseif ( ! $is_low_fetchpriority ) { 6356 // Only add `loading="lazy"` if the feature is enabled. 6357 if ( wp_lazy_loading_enabled( $tag_name, $context ) ) { 6358 $loading_attrs['loading'] = 'lazy'; 6359 } 6360 } 6361 6362 /* 6363 * If flag was set based on contextual logic above, increase the content 6364 * media count, either unconditionally, or based on whether the image size 6365 * is larger than the threshold. This does not apply when the IMG has 6366 * fetchpriority=auto because it may be conditionally displayed by viewport 6367 * size. 6368 */ 6369 if ( 'auto' !== $existing_fetchpriority ) { 6370 if ( $increase_count ) { 6371 wp_increase_content_media_count(); 6372 } elseif ( $maybe_increase_count ) { 6373 /** This filter is documented in wp-includes/media.php */ 6374 $wp_min_priority_img_pixels = apply_filters( 'wp_min_priority_img_pixels', 50000 ); 6375 6376 if ( $wp_min_priority_img_pixels <= $attr['width'] * $attr['height'] ) { 6377 wp_increase_content_media_count(); 6378 } 6379 } 6380 } 6381 6382 /** 6383 * Filters the loading optimization attributes. 6384 * 6385 * @since 6.4.0 6386 * 6387 * @param array $loading_attrs The loading optimization attributes. 6388 * @param string $tag_name The tag name. 6389 * @param array $attr Array of the attributes for the tag. 6390 * @param string $context Context for the element for which the loading optimization attribute is requested. 6391 */ 6392 return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context ); 6393 } 6394 6395 /** 6396 * Gets the threshold for how many of the first content media elements to not lazy-load. 6397 * 6398 * This function runs the {@see 'wp_omit_loading_attr_threshold'} filter, which uses a default threshold value of 3. 6399 * The filter is only run once per page load, unless the `$force` parameter is used. 6400 * 6401 * @since 5.9.0 6402 * 6403 * @param bool $force Optional. If set to true, the filter will be (re-)applied even if it already has been before. 6404 * Default false. 6405 * @return int The number of content media elements to not lazy-load. 6406 */ 6407 function wp_omit_loading_attr_threshold( $force = false ) { 6408 static $omit_threshold; 6409 6410 // This function may be called multiple times. Run the filter only once per page load. 6411 if ( ! isset( $omit_threshold ) || $force ) { 6412 /** 6413 * Filters the threshold for how many of the first content media elements to not lazy-load. 6414 * 6415 * For these first content media elements, the `loading` attribute will be omitted. By default, this is the case 6416 * for only the very first content media element. 6417 * 6418 * @since 5.9.0 6419 * @since 6.3.0 The default threshold was changed from 1 to 3. 6420 * 6421 * @param int $omit_threshold The number of media elements where the `loading` attribute will not be added. Default 3. 6422 */ 6423 $omit_threshold = apply_filters( 'wp_omit_loading_attr_threshold', 3 ); 6424 } 6425 6426 return $omit_threshold; 6427 } 6428 6429 /** 6430 * Increases an internal content media count variable. 6431 * 6432 * @since 5.9.0 6433 * @access private 6434 * 6435 * @param int $amount Optional. Amount to increase by. Default 1. 6436 * @return int The latest content media count, after the increase. 6437 */ 6438 function wp_increase_content_media_count( $amount = 1 ) { 6439 static $content_media_count = 0; 6440 6441 $content_media_count += $amount; 6442 6443 return $content_media_count; 6444 } 6445 6446 /** 6447 * Determines whether to add `fetchpriority='high'` to loading attributes. 6448 * 6449 * @since 6.3.0 6450 * @since 7.0.0 Support is added for IMG tags with `fetchpriority='low'` and `fetchpriority='auto'`. 6451 * @access private 6452 * 6453 * @param array<string, string> $loading_attrs Array of the loading optimization attributes for the element. 6454 * @param string $tag_name The tag name. 6455 * @param array<string, mixed> $attr Array of the attributes for the element. 6456 * @return array<string, string> Updated loading optimization attributes for the element. 6457 */ 6458 function wp_maybe_add_fetchpriority_high_attr( $loading_attrs, $tag_name, $attr ) { 6459 // For now, adding `fetchpriority="high"` is only supported for images. 6460 if ( 'img' !== $tag_name ) { 6461 return $loading_attrs; 6462 } 6463 6464 $existing_fetchpriority = $attr['fetchpriority'] ?? null; 6465 if ( null !== $existing_fetchpriority && 'auto' !== $existing_fetchpriority ) { 6466 /* 6467 * When an IMG has been explicitly marked with `fetchpriority=high`, then honor that this is the element that 6468 * should have the priority. In contrast, the Navigation block may add `fetchpriority=low` to an IMG which 6469 * appears in the Navigation Overlay; such images should never be considered candidates for 6470 * `fetchpriority=high`. Lastly, block visibility may add `fetchpriority=auto` to an IMG when the block is 6471 * conditionally displayed based on viewport size. Such an image is considered an LCP element candidate if it 6472 * exceeds the threshold for the minimum number of square pixels. 6473 */ 6474 if ( 'high' === $existing_fetchpriority ) { 6475 $loading_attrs['fetchpriority'] = 'high'; 6476 wp_high_priority_element_flag( false ); 6477 } 6478 6479 return $loading_attrs; 6480 } 6481 6482 // Lazy-loading and `fetchpriority="high"` are mutually exclusive. 6483 if ( isset( $loading_attrs['loading'] ) && 'lazy' === $loading_attrs['loading'] ) { 6484 return $loading_attrs; 6485 } 6486 6487 if ( ! wp_high_priority_element_flag() ) { 6488 return $loading_attrs; 6489 } 6490 6491 /** 6492 * Filters the minimum square-pixels threshold for an image to be eligible as the high-priority image. 6493 * 6494 * @since 6.3.0 6495 * 6496 * @param int $threshold Minimum square-pixels threshold. Default 50000. 6497 */ 6498 $wp_min_priority_img_pixels = apply_filters( 'wp_min_priority_img_pixels', 50000 ); 6499 6500 if ( $wp_min_priority_img_pixels <= $attr['width'] * $attr['height'] ) { 6501 if ( 'auto' !== $existing_fetchpriority ) { 6502 $loading_attrs['fetchpriority'] = 'high'; 6503 } 6504 wp_high_priority_element_flag( false ); 6505 } 6506 6507 return $loading_attrs; 6508 } 6509 6510 /** 6511 * Accesses a flag that indicates if an element is a possible candidate for `fetchpriority='high'`. 6512 * 6513 * @since 6.3.0 6514 * @access private 6515 * 6516 * @param bool $value Optional. Used to change the static variable. Default null. 6517 * @return bool Returns true if the high-priority element was not already marked. 6518 */ 6519 function wp_high_priority_element_flag( $value = null ): bool { 6520 static $high_priority_element = true; 6521 6522 if ( is_bool( $value ) ) { 6523 $high_priority_element = $value; 6524 } 6525 6526 return $high_priority_element; 6527 } 6528 6529 /** 6530 * Determines the output format for the image editor. 6531 * 6532 * @since 6.7.0 6533 * @access private 6534 * 6535 * @param string $filename Path to the image. 6536 * @param string $mime_type The source image mime type. 6537 * @return array<string, string> An array of mime type mappings. 6538 */ 6539 function wp_get_image_editor_output_format( $filename, $mime_type ) { 6540 $output_format = array( 6541 'image/heic' => 'image/jpeg', 6542 'image/heif' => 'image/jpeg', 6543 'image/heic-sequence' => 'image/jpeg', 6544 'image/heif-sequence' => 'image/jpeg', 6545 ); 6546 6547 /** 6548 * Filters the image editor output format mapping. 6549 * 6550 * Enables filtering the mime type used to save images. By default HEIC/HEIF images 6551 * are converted to JPEGs. 6552 * 6553 * @see WP_Image_Editor::get_output_format() 6554 * 6555 * @since 5.8.0 6556 * @since 6.7.0 The default was changed from an empty array to an array 6557 * containing the HEIC/HEIF images mime types. 6558 * 6559 * @param array<string, string> $output_format An array of mime type mappings. Maps a source mime type to a new 6560 * destination mime type. By default maps HEIC/HEIF input to JPEG output. 6561 * @param string $filename Path to the image. 6562 * @param string $mime_type The source image mime type. 6563 */ 6564 return apply_filters( 'image_editor_output_format', $output_format, $filename, $mime_type ); 6565 } 6566 6567 /** 6568 * Checks whether client-side media processing is enabled. 6569 * 6570 * Client-side media processing uses the browser's capabilities to handle 6571 * tasks like image resizing and compression before uploading to the server. 6572 * 6573 * @since 7.1.0 6574 * 6575 * @return bool Whether client-side media processing is enabled. 6576 */ 6577 function wp_is_client_side_media_processing_enabled(): bool { 6578 // This is due to SharedArrayBuffer requiring a secure context. 6579 $host = strtolower( (string) strtok( $_SERVER['HTTP_HOST'] ?? '', ':' ) ); 6580 $enabled = ( is_ssl() || 'localhost' === $host || str_ends_with( $host, '.localhost' ) ); 6581 6582 /** 6583 * Filters whether client-side media processing is enabled. 6584 * 6585 * @since 7.1.0 6586 * 6587 * @param bool $enabled Whether client-side media processing is enabled. Default true if the page is served in a secure context. 6588 */ 6589 return (bool) apply_filters( 'wp_client_side_media_processing_enabled', $enabled ); 6590 } 6591 6592 /** 6593 * Sets a global JS variable to indicate that client-side media processing is enabled. 6594 * 6595 * @since 7.1.0 6596 */ 6597 function wp_set_client_side_media_processing_flag(): void { 6598 if ( ! wp_is_client_side_media_processing_enabled() ) { 6599 return; 6600 } 6601 6602 wp_add_inline_script( 'wp-block-editor', 'window.__clientSideMediaProcessing = true;', 'before' ); 6603 6604 $chromium_version = wp_get_chromium_major_version(); 6605 6606 if ( null !== $chromium_version && $chromium_version >= 137 ) { 6607 wp_add_inline_script( 'wp-block-editor', 'window.__documentIsolationPolicy = true;', 'before' ); 6608 } 6609 } 6610 6611 /** 6612 * Returns the major Chrome/Chromium version from the current request's User-Agent. 6613 * 6614 * Matches all Chromium-based browsers (Chrome, Edge, Opera, Brave). 6615 * 6616 * @since 7.1.0 6617 * 6618 * @return int|null The major Chrome version, or null if not a Chromium browser. 6619 */ 6620 function wp_get_chromium_major_version(): ?int { 6621 if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) { 6622 return null; 6623 } 6624 if ( preg_match( '#Chrome/(\d+)#', $_SERVER['HTTP_USER_AGENT'], $matches ) ) { 6625 return (int) $matches[1]; 6626 } 6627 return null; 6628 } 6629 6630 /** 6631 * Enables cross-origin isolation in the block editor. 6632 * 6633 * Required for enabling SharedArrayBuffer for WebAssembly-based 6634 * media processing in the editor. Uses Document-Isolation-Policy 6635 * on supported browsers (Chromium 137+). 6636 * 6637 * Skips setup when a third-party page builder overrides the block 6638 * editor via a custom `action` query parameter, as DIP would block 6639 * same-origin iframe access that these editors rely on. 6640 * 6641 * @since 7.1.0 6642 */ 6643 function wp_set_up_cross_origin_isolation(): void { 6644 if ( ! wp_is_client_side_media_processing_enabled() ) { 6645 return; 6646 } 6647 6648 $screen = get_current_screen(); 6649 6650 if ( ! $screen ) { 6651 return; 6652 } 6653 6654 if ( ! $screen->is_block_editor() && 'site-editor' !== $screen->id && ! ( 'widgets' === $screen->id && wp_use_widgets_block_editor() ) ) { 6655 return; 6656 } 6657 6658 /* 6659 * Skip when rendering the classic-theme home route, which shows the site 6660 * preview in an iframe and must reach its `contentDocument` to neutralize 6661 * interactive elements. DIP would block that same-origin access. 6662 * 6663 * Keyed off $pagenow rather than the current screen so the guard keeps 6664 * working if the header set-up is ever moved to an earlier hook (such as 6665 * admin_init) where the screen is not yet available. 6666 */ 6667 global $pagenow; 6668 6669 // phpcs:ignore WordPress.Security.NonceVerification.Recommended 6670 if ( 'site-editor.php' === $pagenow && ! wp_is_block_theme() && ( ! isset( $_GET['p'] ) || '/' === $_GET['p'] ) ) { 6671 return; 6672 } 6673 6674 /* 6675 * Skip when a third-party page builder overrides the block editor. 6676 * DIP isolates the document into its own agent cluster, 6677 * which blocks same-origin iframe access that these editors rely on. 6678 */ 6679 if ( isset( $_GET['action'] ) && 'edit' !== $_GET['action'] ) { 6680 return; 6681 } 6682 6683 // Cross-origin isolation is not needed if users can't upload files anyway. 6684 if ( ! current_user_can( 'upload_files' ) ) { 6685 return; 6686 } 6687 6688 wp_start_cross_origin_isolation_output_buffer(); 6689 } 6690 6691 /** 6692 * Sends the Document-Isolation-Policy header for cross-origin isolation. 6693 * 6694 * Uses an output buffer to add crossorigin="anonymous" where needed. 6695 * 6696 * @since 7.1.0 6697 */ 6698 function wp_start_cross_origin_isolation_output_buffer(): void { 6699 $chromium_version = wp_get_chromium_major_version(); 6700 6701 if ( null === $chromium_version || $chromium_version < 137 ) { 6702 return; 6703 } 6704 6705 ob_start( 6706 static function ( string $output ): string { 6707 header( 'Document-Isolation-Policy: isolate-and-credentialless' ); 6708 6709 return wp_add_crossorigin_attributes( $output ); 6710 } 6711 ); 6712 } 6713 6714 /** 6715 * Adds crossorigin="anonymous" to relevant tags in the given HTML string. 6716 * 6717 * @since 7.1.0 6718 * 6719 * @param string $html HTML input. 6720 * @return string Modified HTML. 6721 */ 6722 function wp_add_crossorigin_attributes( string $html ): string { 6723 $site_url = site_url(); 6724 6725 $processor = new WP_HTML_Tag_Processor( $html ); 6726 6727 // See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin. 6728 $cross_origin_tag_attributes = array( 6729 'AUDIO' => array( 'src' ), 6730 'LINK' => array( 'href' ), 6731 'SCRIPT' => array( 'src' ), 6732 'VIDEO' => array( 'src', 'poster' ), 6733 'SOURCE' => array( 'src' ), 6734 ); 6735 6736 while ( $processor->next_tag() ) { 6737 $tag = $processor->get_tag(); 6738 6739 if ( ! isset( $cross_origin_tag_attributes[ $tag ] ) ) { 6740 continue; 6741 } 6742 $crossorigin = $processor->get_attribute( 'crossorigin' ); 6743 if ( null !== $crossorigin ) { 6744 continue; 6745 } 6746 6747 if ( 'AUDIO' === $tag || 'VIDEO' === $tag ) { 6748 $processor->set_bookmark( 'audio-video-parent' ); 6749 } 6750 6751 $processor->set_bookmark( 'resume' ); 6752 6753 $sought = false; 6754 6755 $is_cross_origin = false; 6756 6757 foreach ( $cross_origin_tag_attributes[ $tag ] as $attr ) { 6758 $url = $processor->get_attribute( $attr ); 6759 if ( is_string( $url ) && ! str_starts_with( $url, $site_url ) && ! str_starts_with( $url, '/' ) ) { 6760 $is_cross_origin = true; 6761 } 6762 6763 if ( $is_cross_origin ) { 6764 break; 6765 } 6766 } 6767 6768 if ( $is_cross_origin ) { 6769 if ( 'SOURCE' === $tag ) { 6770 $sought = $processor->seek( 'audio-video-parent' ); 6771 6772 if ( $sought ) { 6773 $processor->set_attribute( 'crossorigin', 'anonymous' ); 6774 } 6775 } else { 6776 $processor->set_attribute( 'crossorigin', 'anonymous' ); 6777 } 6778 6779 if ( $sought ) { 6780 $processor->seek( 'resume' ); 6781 $processor->release_bookmark( 'audio-video-parent' ); 6782 } 6783 } 6784 } 6785 6786 return $processor->get_updated_html(); 6787 } 6788
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Thu Jul 30 08:20:17 2026 | Cross-referenced by PHPXref |