WordPress og_image automation

Automatically Setting og:image in WordPress

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.

Shou Arisaka
3 min read
Sep 2, 2022

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.

Image

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:

  1. Literally all pages get the same og:image. You can't set individual images
  2. 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:

  1. Change `$og_default = 'https://yuis-programming.com/android-chrome-512x512.png';` to your default image URL path
  2. 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:

  1. Checks if a `` HTML tag already exists in the HTML; if not, proceeds
  2. Gets img image tags from the HTML and retrieves their src attributes. If the URL matches the specified regex pattern, proceeds
  3. Creates og:image and twitter:image tags with the retrieved URL and inserts them just before `` in the HTML
  4. 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

Image

Nice! 👍

Share this article

Shou Arisaka Sep 2, 2022

🔗 Copy Links