Skip to content

Instantly share code, notes, and snippets.

@jdevalk
Last active November 1, 2024 10:12
Show Gist options
  • Save jdevalk/90250f4559e95ca0fe357150a4d574de to your computer and use it in GitHub Desktop.
Save jdevalk/90250f4559e95ca0fe357150a4d574de to your computer and use it in GitHub Desktop.
Replace og:image .avif to .jpg
<?php
/*
* Plugin Name: Replace og:image .avif to .jpg
* Description: Replaces og:image URLs ending in -jpg.avif with .jpg in the page output. Uses the new WP_HTML_Tag_Processor.
*/
add_action( 'template_redirect' , function() {
ob_start( 'joost_replace_og_avif_with_jpg' );
});
function joost_replace_og_avif_with_jpg( $buffer ) {
// Initialize the HTML Tag Processor.
$processor = new WP_HTML_Tag_Processor( $buffer );
// Loop through each <meta> tag in the HTML output.
while ( $processor->next_tag( 'meta' ) ) {
// Remove the "class="yoast-seo-meta-tag"" in the process.
$processor->remove_attribute( 'class' );
// Check if it has the `property` attribute with the value `og:image`.
if ( $processor->get_attribute( 'property' ) === 'og:image' ) {
// Get the current content attribute.
$content = $processor->get_attribute( 'content' );
// Check if the content URL ends with .avif.
if ( $content && strpos( $content, '-jpg.avif' ) !== false ) {
// Replace .avif with .jpg in the content attribute.
$updated_content = str_replace( '-jpg.avif', '.jpg', $content );
$processor->set_attribute( 'content', $updated_content );
}
}
}
// Output the modified HTML.
return $processor->get_updated_html();
}
<?php
/*
* Plugin Name: Replace og:image .avif to .jpg
* Description: Replaces og:image URLs ending in -jpg.avif with .jpg in the page output.
*/
add_action(
'template_redirect',
function() {
ob_start( 'joost_replace_og_image_avif_with_jpg' );
}
);
function joost_replace_og_image_avif_with_jpg( $buffer ) {
// Replace "-jpg.avif" with ".jpg" in og:image meta tags.
return preg_replace('/(<meta\s+property="og:image"\s+content="[^"]+)-jpg\.avif(")/i', '$1.jpg$2', $buffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment