Skip to content

Instantly share code, notes, and snippets.

@PatelUtkarsh
Created May 26, 2020 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatelUtkarsh/8e100622bbd8316137858c3f559f6b45 to your computer and use it in GitHub Desktop.
Save PatelUtkarsh/8e100622bbd8316137858c3f559f6b45 to your computer and use it in GitHub Desktop.
AMP Extract Image without external request
<?php
add_filter( 'amp_extract_image_dimensions_batch', function ( $dimensions ) {
$home_url = get_home_url();
foreach ( $dimensions as $url => &$data ) {
if ( false !== strpos( $url, $home_url ) ) {
$attachment_id = wpcom_vip_attachment_url_to_postid( $url );
if ( false !== $attachment_id ) {
$src = wp_get_attachment_image_src( $attachment_id );
$height = $src[1];
$width = $src[2];
if ( ! empty( $height ) && ! empty( $width ) ) {
$data = [
'width' => $width,
'height' => $height,
];
}
}
}
}
return $dimensions;
} );
add_action( 'amp_extract_image_dimensions_batch_callbacks_registered', function () {
$callback = [
'AMP_Image_Dimension_Extractor',
'extract_by_downloading_images',
];
if ( has_filter( 'amp_extract_image_dimensions_batch', $callback ) ) {
remove_filter( 'amp_extract_image_dimensions_batch', $callback, 999 );
}
} );
@PatelUtkarsh
Copy link
Author

PatelUtkarsh commented May 26, 2020

See ampproject/amp-wp@3e6f1ac

Also see this might cause issue with large DB: ampproject/amp-wp#651 (This gist is adding query back which was removed).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment