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