Using amp-img tags can allow you to use images in AMP. To convert img tags to amp-img tags in WordPress, you must use the custom shortcode WPZA developers have developed.
2 answers
1
Register the amp-img shortcode
You need to start by adding the code snippet below to your WordPress theme’s functions.php file.
- Open your WordPress theme’s function.php file by using the WordPress Theme Editor (Appearance > Editor > Theme Functions);
- Copy and paste the code below;
- Click Update File to save the changes.
function amp_imgs( $atts ) {
$atts = shortcode_atts(
array(
'image' => 'default-image.jpg',
'alt' => ''
),
$atts,
'amp-img'
);
$sizes = explode( ' ', getimagesize( $atts['image'] )[3] );
$output = '<amp-img src="' . $atts['image'] . '" alt="' . $atts['alt'] . '" ' . $sizes[0] . ' ' . $sizes[1] . ' layout="responsive"></amp-img>';
return $output;
}
add_shortcode( 'amp-img', 'amp_imgs' );
Automatically converting img tags to amp-img tags using a shortcode
Once you’ve added the above shortcode function to your WordPress theme’s functions.php file, use the steps below to start converting img tags to amp-img tags automatically.
- Open any page on your WordPress website and call the shortcode;
- Add the attribute image with the image’s URL;
- Add the attribute alt with the image’s alt text for accessibility purposes.
[amp-img image="example.jpg" alt="The alt text example"]
— Support WizardAnswer 1
0
Get the amp-img shortcode plugin
We’ve made it really easy for you to use the amp-img tag in your WordPress Posts by developing the above code into a plugin.
You can find the plugin over at the WordPress plugin repository.
— Support WizardAnswer 2