How to use Open Graph to make your content easily recognizable by social networks

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!

from WpRecipes.com http://feedproxy.google.com/~r/Wprecipes/~3/U0Lql9h18kM/how-to-use-open-graph-to-make-your-content-easily-recognizable-by-social-networks

About these ads

Kommentar verfassen

Bitte logge dich mit einer dieser Methoden ein, um deinen Kommentar zu veröffentlichen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ photo

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s