Created
October 27, 2025 20:03
-
-
Save westonruter/8571a91675e1886e34304f8bc76a13fb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Plugin Name: Try Featured Image as OG Image | |
| */ | |
| function apply_wp_content_img_tag_filters( string $markup, int $attachment_id ): string { | |
| return apply_filters( 'wp_content_img_tag', $markup, '', $attachment_id ); | |
| } | |
| add_action( | |
| 'wp', | |
| static function () { | |
| if ( ! is_singular() || ! get_post_thumbnail_id() ) { | |
| return; | |
| } | |
| add_action( | |
| 'wp_head', | |
| function () { | |
| $url = get_the_post_thumbnail_url( null, 'thumbnail' ); | |
| printf( '<meta name="og:image" class="get_the_post_thumbnail_url" content="%s">' . PHP_EOL, esc_url( $url ) ); | |
| printf( '<meta name="og:image" class="wp_get_attachment_image_url" content="%s">' . PHP_EOL, esc_url( wp_get_attachment_image_url( get_post_thumbnail_id() ) ) ); | |
| } | |
| ); | |
| } | |
| ); | |
| add_action( | |
| 'wp_body_open', | |
| function () { | |
| if ( ! is_singular() || ! get_post_thumbnail_id() ) { | |
| return; | |
| } | |
| echo "\n"; | |
| // Failure 1: | |
| $url = get_the_post_thumbnail_url( null, 'thumbnail' ); | |
| printf( "get_the_post_thumbnail_url:\n<img src='%s'>\n\n", esc_url( $url ) ); | |
| // Failure 2: | |
| $img_tag = wp_get_attachment_image( get_post_thumbnail_id(), 'thumbnail' ); | |
| echo "wp_get_attachment_image:\n$img_tag\n\n"; | |
| // Workaround 1: | |
| echo "wp_content_img_tag(get_the_post_thumbnail_url):\n"; | |
| $markup = sprintf( "<img src='%s'>", get_the_post_thumbnail_url( null, 'thumbnail' ) ); | |
| echo apply_filters( 'wp_content_img_tag', $markup, '', get_post_thumbnail_id() ) . "\n\n"; | |
| // Workaround 2: | |
| echo "wp_content_img_tag(wp_get_attachment_image):\n"; | |
| $markup = wp_get_attachment_image( get_post_thumbnail_id(), 'thumbnail' ); | |
| echo apply_filters( 'wp_content_img_tag', $markup, '', get_post_thumbnail_id() ) . "\n\n"; | |
| // Workaround 3" | |
| $markup = wp_get_attachment_image( get_post_thumbnail_id(), 'thumbnail', false, array( 'class' => 'wp-image-' . get_post_thumbnail_id() ) ); | |
| echo "the_content(wp_get_attachment_image):\n" . apply_filters( 'the_content', $markup ) . "\n\n"; | |
| } | |
| ); | |
| $img = apply_filters( | |
| 'wp_content_img_tag', | |
| wp_get_attachment_image( get_post_thumbnail_id(), 'large' ), '', | |
| get_post_thumbnail_id() | |
| ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment