| 1 |
<?php |
| 2 |
/** |
| 3 |
* Hook callbacks used for Fetchpriority. |
| 4 |
* |
| 5 |
* @package performance-lab |
| 6 |
* @since 2.1.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
/** |
| 10 |
* Filters an image tag in content to add the fetchpriority attribute if it is not lazy-loaded. |
| 11 |
* |
| 12 |
* @since 1.8.0 |
| 13 |
* |
| 14 |
* @param string $filtered_image The image tag to filter. |
| 15 |
* @param string $context The context of the image. |
| 16 |
* @return string The filtered image tag. |
| 17 |
*/ |
| 18 |
function fetchpriority_img_tag_add_attr( $filtered_image, $context ) { |
| 19 |
|
| 20 |
if ( 'the_content' !== $context && 'the_post_thumbnail' !== $context ) { |
| 21 |
return $filtered_image; |
| 22 |
} |
| 23 |
|
| 24 |
// Fetchpriority relies on lazy loading logic. |
| 25 |
if ( ! wp_lazy_loading_enabled( 'img', $context ) ) { |
| 26 |
return $filtered_image; |
| 27 |
} |
| 28 |
|
| 29 |
if ( ! empty( $filtered_image ) && strpos( $filtered_image, 'loading="lazy"' ) === false && strpos( $filtered_image, 'fetchpriority=' ) === false ) { |
| 30 |
$filtered_image = str_replace( '<img ', '<img fetchpriority="high" ', $filtered_image ); |
| 31 |
remove_filter( 'wp_content_img_tag', 'fetchpriority_img_tag_add_attr' ); |
| 32 |
remove_filter( 'post_thumbnail_html', 'fetchpriority_filter_post_thumbnail_html' ); |
| 33 |
} |
| 34 |
|
| 35 |
return $filtered_image; |
| 36 |
} |
| 37 |
add_filter( 'wp_content_img_tag', 'fetchpriority_img_tag_add_attr', 10, 2 ); |
| 38 |
|
| 39 |
/** |
| 40 |
* Filters the post thumbnail HTML to conditionally add the fetchpriority attribute. |
| 41 |
* |
| 42 |
* @since 1.8.0 |
| 43 |
* |
| 44 |
* @param string $html The post thumbnail HTML to filter. |
| 45 |
* @return string The filtered post thumbnail HTML. |
| 46 |
*/ |
| 47 |
function fetchpriority_filter_post_thumbnail_html( $html ) { |
| 48 |
$html = fetchpriority_img_tag_add_attr( $html, 'the_post_thumbnail' ); |
| 49 |
|
| 50 |
return $html; |
| 51 |
} |
| 52 |
add_filter( 'post_thumbnail_html', 'fetchpriority_filter_post_thumbnail_html' ); |
| 53 |
|