Add Open Graph Protocol Markup to Any WordPress Theme

Rich objects in a social graphs

When you share a link on Facebook, an image from the link is shown, usually. Sometimes, no image is displayed, as if Facebook couldn’t find a suitable image at the URL.


Adding Open Graph protocol tags to your site will ensure that Facebook knows which image to use when someone shares a page on your website. Open Graph markup is similar to markup. Both allow you to define values for certain aspects of your website, as seen by other sites like Facebook, Twitter, and many other social media sites.


There’s a couple of ways we can do this. You can use a plugin, like Open Graph Protocol Framework, or you can add Open Graph markup to your WordPress theme manually.

We’ll be covering how to add Open Graph markup to your theme manually. Especially useful for theme developers who want to build Open Graph protocol support into their themes.

The markup we’ll be adding can be seen in this GitHub gist:

Most of that should be pretty self-explanatory.

The og:type property is the only tag that needs explanation, as there’s only certain values that are valid. Most of the time, you’ll probably be setting the og:type property to article or website. A list of other Open Graph protocol object types can be found at the Open Graph protocol site.

The Code

Every Open Graph property will be set on-the-fly, depending on which post or page is being viewed or shared. To add the necessary markup, we need to use the add_action WordPress function inside your theme’s functions.php file. Here’s how I’ve been handing it:

Comments are open below, feel free to ask questions or tell me how wrong I am on one point or another. 🙂

  • Javier Ruiz Morales

    if the post doesn’t have an image, where i put the url of the image that i want set for default, here: $image = ‘url image here’;

    • Right, in functions.php, line 11 you can specify the default image URL if no image is set for a post or page.

      See below, especially the comment as it has an example:

      And here’s the example from the comment on the GitHub file:

      If no image is set for a post or page, the $image variable can set or dynamically constructed to point to an image on your server. To point it to a static file, line 11 would look like:
      $image = '';

  • I added this code in my functions.php file… it works exactly as I wanted it to.
    but now http://[mysite].com/wp-admin returns nothing but a blank page… why is that so?

    when I remove this code from functions.php , it works fine… ???