Optimize Your WordPress Website for Facebook with OpenGraph

Originally Posted on November 23, 2013Last Updated on December 9, 2013

Never heard of OpenGraph? Or maybe you have, but aren’t sure just how to go about it.

Briefly, OpenGraph is this set of meta tags we can use on our site to give us more control over how our content is shared on Facebook (primarily), and to a lesser degree other sites like Google+ and Pinterest. You can read all about it at ogp.me, but if you just want to copy and paste some code, you can grab that here and I’ll explain below what each piece means. This can all go in your header.php file, before the closing <head> tag.

One at a Time Please, What are all of these OpenGraph tags for?

Sure! I wouldn’t expect you to just paste a bunch of code into your site which could easily bring about the demise of the entire southeastern coastal environment of Antarctica. So let’s look at what each piece does:

Sets the Title displayed when someone shares this page on Facebook: Though this can be edited by the user, this is what FB will show by default. Here were say “If it’s the homepage of your WordPress site, show the name of the site and your tagline.” Otherwise, “show the title of the page and then via Your Site’s Name“.<meta property="og:title" content="<?php if (is_front_page()) { echo get_bloginfo ( 'name' ); echo get_bloginfo( 'description' ); } else { echo get_the_title() . ' via '.get_bloginfo ( 'name' ); } ?>" />

Tell Facebook your website is a website: Other options are article, music, video, book, and more but those seem to be the major ones respected.<meta property="og:type" content="website" />

Sets the link back to your site: Some WordPress pages can actually be accessed by multiple URLs. If you’re not setting up canonical URLs correctly, you’ll want to get on that. In fact, you could use the information from that link and combine it with this post to get something even better. Let me know if you end up doing that, in the comments.<meta property="og:url" content="<?php the_permalink(); ?>" />

Set the text snippet shown when someone shares your page on Facebook: This will just grab the excerpt, whether customized or created on the fly by WP.<meta property="og:description" content="<?php the_excerpt_rss(); ?>" />

Set the image shown when your page is shared on Facebook: Next up we tell WordPress to fetch the page, post, etc.’s post thumbnail as the image we want Facebook to show when our page is shared. You could setup an else statement to show another default image when no post thumnbail is available.<?php if (has_post_thumbnail()) { ?>
<meta property="og:image" content="<?php $attachment_id = get_post_thumbnail_id( $post->ID ); $image_attributes = wp_get_attachment_image_src( $attachment_id, 'full' ); echo $image_attributes[0]; ?>">