All WordPress snippets
WordPress

Basic Open Graph Meta Tags for Single Posts

Outputs Open Graph title, description, and image tags on single posts — useful groundwork if you're not running an SEO plugin yet.

php
/**
 * Add Open Graph Meta Tags
 */
function meta_og() {
    global $post;

    if ( is_single() ) {
        if( has_post_thumbnail( $post->ID ) ) {
            $img_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
        } 
        $excerpt = strip_tags( $post->post_content );
        $excerpt_more = '';
	
        if ( strlen($excerpt ) > 155) {
            $excerpt = substr( $excerpt,0,155 );
            $excerpt_more = ' ...';
        }
	
        $excerpt = str_replace( '"', '', $excerpt );
        $excerpt = str_replace( "'", '', $excerpt );
        $excerptwords = preg_split( '/[nrt ]+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY );
        array_pop( $excerptwords );
        $excerpt = implode( ' ', $excerptwords ) . $excerpt_more; ?>
	
        <meta name="author" content="Your Name">
        <meta name="description" content="<?php echo $excerpt; ?>">
        <meta property="og:title" content="<?php echo the_title(); ?>">
        <meta property="og:description" content="<?php echo $excerpt; ?>">
        <meta property="og:type" content="article">
        <meta property="og:url" content="<?php echo the_permalink(); ?>">
        <meta property="og:site_name" content="Your Site Name">
        <meta property="og:image" content="<?php echo $img_src[0]; ?>"><?php
    } else {
        return;
    }
}

add_action('wp_head', 'meta_og', 5);
Want your own copy? Fork this repo and build your own snippet collection. Fork on GitHub →