So I have code in place to remove the first image of all posts (this is because I put an image at the top of every post before featured images were introduced, and once featured images were created, I just put code in place to remove the first image so I wouldn't have to go back and do it manually). I'm trying to get it work for AMP pages, but haven't been able to figure it out yet.
This is the function for the normal pages.
function remove_first_image ($content) {
if (!is_page() && !is_feed() && !is_feed() && !is_home()) {
$content = preg_replace("/<img[^>]+\>/i", "", $content, 1);
}
return $content;
}
add_filter('the_content', 'remove_first_image');
And since that doesn't remove the first image on AMP pages, I tried something like this which has some correct elements in it but isn't working.
add_action( 'pre_amp_render_post', function () {
add_filter( 'the_content', function( $content ){
$content = preg_replace("/<img[^>]+\>/i", "", $content, 1);
return $content;
}, 3 );
});
Any thoughts on how to get this to work for AMP content?
I think the code example you listed above is to use with the AMP plugin from Automattic https://wordpress.org/plugins/amp/.
Are you using a different AMP plugin... I saw reference to wp-amp-ninja. You might have to check their code to find the actions and filters. It may not be the same... and then you won't be positive they don't change this in updates, if it's not properly documented.
You can try switching to the Automattic one. Or if you're using the premium version of the wp-amp-ninja plugin, I see they offer CSS options in the upgrade.
Like I mention, I think your code will work with the Automattic plugin. If you switch to it and out of interest, want to try remove the image with styles instead of the_content
filter... That is, if the 2 images still appear... Use the amp_post_template_css
action. Use the browser's inspect element to find the correct css class name. (might be: amp-img.wp-post-image)
function wp_amp_additional_css_styles( $amp_template ) {
?>
amp-img.wp-post-image {
display: none;
}
<?php
}
add_action( 'amp_post_template_css', 'wp_amp_additional_css_styles' );