This article explains and introduces how to automatically set og:image and twitter:image HTML meta tags in WordPress by retrieving the first image from a post.

We’ll explain the steps and PHP code for automatically setting og:image and twitter:image HTML meta tags in WordPress by retrieving the first image from a post.
By the way, last week I improved the SEO and page loading speed of this site based on SEO analysis from PageSpeed Insights and Chrome’s Lighthouse. As part of this, I encountered things like PWA (Progressive Web Apps), icons, and favicons - basically image-related matters.
That’s when I remembered that I hadn’t set up og:image for sharing on Twitter, Discord, etc.
Setting og:image and twitter:image for all WordPress pages is simple. You just need to paste the following HTML into your theme’s header.php:
<meta property="og:image" content="https://yuis-programming.com/android-chrome-512x512.png">
<meta name="twitter:image" content="https://yuis-programming.com/android-chrome-512x512.png" />
However, the problems with this are:
- Literally all pages get the same og:image. You can't set individual images
- If an og:image is already defined, it will be overwritten, or there will be duplicates/conflicts
So I wrote the following PHP:
function callback02($buffer) {
$dom = new DOMDocument();
$dom->loadHTML($buffer);
$xpath = new DOMXPath($dom);
$og_image = $xpath->query('//meta[contains(@property, "og:image")]')->item(0);
if ($og_image == null) {
for ($x = 0; $x <= 3; $x++) {
if ($x == 3) {
$og_default = 'https://yuis-programming.com/android-chrome-512x512.png';
$buffer = str_replace('</head>', '<meta property="og:image" content="' . $og_default . '">
<meta name="twitter:image" content="' . $og_default . '" />
</head>', $buffer);
break;
}
$d = $xpath->query('//main/article//img')->item($x);
if ($d !== null) {
$i = $d->getAttribute("src");
$m = preg_match('/yuis\.xsrv\.jp\/(data|images)\/.*(jpe?g|png|webp)($|\?)/',$i,$matches);
if ($m == 1) {
$buffer = str_replace('</head>', '<meta property="og:image" content="' . $i . '">
<meta name="twitter:image" content="' . $i . '" />
</head>', $buffer);
break;
}
}
}
}
return $buffer;
}
ob_start("callback02");
When using this:
- Change `$og_default = 'https://yuis-programming.com/android-chrome-512x512.png';` to your default image URL path
- Change `preg_match('/yuis\.xsrv\.jp\/(data|images)\/.*(jpe?g|png|webp)($|\?)/',` to a regex pattern for the image URL paths you want to target in articles
As always, use at your own risk. While the above code theoretically cannot corrupt data or databases, it’s possible that your site might not display, resulting in lost visitors. If the site breaks, just delete the code and save to restore. Always verify that the site displays correctly while using it.
The above program uses ob_start to get and process the PHP buffer, and DOMDocument for HTML parsing.
The code does the following:
- Checks if a `` HTML tag already exists in the HTML; if not, proceeds
- Gets img image tags from the HTML and retrieves their src attributes. If the URL matches the specified regex pattern, proceeds
- Creates og:image and twitter:image tags with the retrieved URL and inserts them just before `` in the HTML
- Repeats the img tag pattern matching about 3 times; if no match, creates tags with the default og:image and inserts them just before ``
The created og:image is recognized correctly as shown in the image above.
Let’s test and verify how the og:image looks.
OpenGraph - Preview Social Media Share and Generate Metatags - OpenGraph

Nice! 👍