OGsmithStart free
← Writing

Automatic Open Graph images in WordPress

· 4 min read

Most WordPress sites share links with whatever image a post happens to have, or none. With a few lines of PHP every post and page gets a card made from its own title, in your colours.

The plugin: no code

Download the OGsmith plugin for WordPress, then upload it under Plugins → Add New → Upload Plugin and activate it. Under Settings → OGsmith, paste your Account ID and signing secret from the dashboard's Signed URLs panel. Every post, page and the home page then gets a card made from its title and excerpt, and the settings page shows a preview.

It works next to Yoast SEO, Rank Math and similar plugins: their image tags are swapped for the card, so each page keeps exactly one og:image. The rest of this post is for doing the same by hand.

Without an SEO plugin

Add this to your child theme's functions.php, or to a code snippets plugin so a theme update doesn't remove it.

add_action('wp_head', function () {
  if (!is_singular()) return;

  $og = add_query_arg([
    'key' => 'og_yourkey',
    'url' => rawurlencode(get_permalink()),
  ], 'https://ogsmith.app/api/og');

  echo '<meta property="og:image" content="' . esc_url($og) . '">' . "\n";
  echo '<meta property="og:image:width" content="1200">' . "\n";
  echo '<meta property="og:image:height" content="630">' . "\n";
  echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
});

add_query_arg doesn't encode values, which is why the permalink goes through rawurlencode. With url, OGsmith reads the post's title and description and builds the card from them.

With Yoast SEO

Yoast already writes the Open Graph tags, so replace its image instead of adding a second one:

function ogsmith_card() {
  return add_query_arg([
    'key' => 'og_yourkey',
    'url' => rawurlencode(get_permalink()),
  ], 'https://ogsmith.app/api/og');
}
add_filter('wpseo_opengraph_image', function ($image) {
  return is_singular() ? ogsmith_card() : $image;
});
add_filter('wpseo_twitter_image', function ($image) {
  return is_singular() ? ogsmith_card() : $image;
});

Your colours and logo

Set the template, accent colour and site name once under Brand defaults in the dashboard (paid plans can add a logo too). Any card that doesn't set its own values uses these, so the snippet above never needs to change.

After saving, paste a post into the link preview checker. If a platform still shows the old image, this explains why and what clears it.