<?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();
}