DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

Created by Facebook, Open Graph is a protocol which allow your blog or website to “talk” to social networks. Here is a super useful code snippet to add to your WordPress site to make it fully Open Graph compliant.

Simply paste the code below into your functions.php file. The snippet will automatically add the Open Graph metadata to the <head> section of your pages.

function wptuts_opengraph_for_posts() {
    if ( is_singular() ) {
        global $post;
        setup_postdata( $post );
        $og_type = '<meta property="og:type" content="article" />' . "\n";
        $og_title = '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '" />' . "\n";
        $og_url = '<meta property="og:url" content="' . get_permalink() . '" />' . "\n";
        $og_description = '<meta property="og:description" content="' . esc_attr( get_the_excerpt() ) . '" />' . "\n";
        if ( has_post_thumbnail() ) {
            $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
            $og_image = '<meta property="og:image" content="' . $imgsrc[0] . '" />' . "\n";
        }
        echo $og_type . $og_title . $og_url . $og_description . $og_image;
    }
}
add_action( 'wp_head', 'wptuts_opengraph_for_posts' );

In order to make your blog fully compliant with the Open Graph protocol, you also have to edit your header.php file and replace the <html> tag by the following:

<html <?php language_attributes(); ?> prefix="og: http://ogp.me/ns#">

Thanks to WP Tuts for the tip!

Tags

7 Comments

  1. Thanks for mentioning my article; I’m proud about my articles being followed by WordPress experts like you guys 🙂

  2. Oh, by the way, I updated the code to prevent the “notice” PHP gives when there’s no thumbnail image. You can check the article for the updated snippet! 🙂

  3. What if you already have these tags added by plugins like Jetpack and Yoasts SEO plugin.

    Should you check your source code first?

    Will duplicate tags be a problem?

  4. And here I thought this Open Graph integration was going to be complicated! Ha. Thanks for this!! I’ll be updating my site tonight!

  5. Brad

    you can use Facebook’s LINT debugger to test. It will inform you of duplicates. OGraphr is a good plug-in if you don’t want to crack open theme files.

  6. I tried this, but now I get a Http-500 error, and I can’t login anymore, my website is turned blank. What should I do?

  7. Have already implemented this feature through Yoast SEO. But very good code to promote our blog through social media.

Leave a Comment

Your email address will not be published. Required fields are marked *