Skip to content

Instantly share code, notes, and snippets.

@paperrobots
Last active September 22, 2016 19:43
Show Gist options
  • Save paperrobots/6444804dafe1e91a24ed2b3c43a62b11 to your computer and use it in GitHub Desktop.
Save paperrobots/6444804dafe1e91a24ed2b3c43a62b11 to your computer and use it in GitHub Desktop.
Add Open Graph tags to Wordpress
function doctype_opengraph($output) {
return $output . '
xmlns:og="http://opengraphprotocol.org/schema/"
xmlns:fb="http://www.facebook.com/2008/fbml"';
}
add_filter('language_attributes', 'doctype_opengraph');
function fb_opengraph() {
global $post;
if(has_post_thumbnail($post->ID)) {
$img_src = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium');
} else {
$img_src = get_stylesheet_directory_uri() . '/img/opengraph_image.jpg';
}
if($post->post_excerpt != '') {
$excerpt = strip_tags($post->post_excerpt);
$excerpt = str_replace("", "'", $excerpt);
} elseif ($post->post_content != ''){
$excerpt = strip_tags($post->post_content);
$excerpt = str_replace("", "'", $excerpt);
$excerpt = wp_trim_words($excerpt, 25);
} else {
$excerpt = get_bloginfo('description');
}
?>
<meta property="og:title" content="<?php echo get_the_title(); ?>"/>
<meta property="og:description" content="<?php echo $excerpt; ?>"/>
<meta property="og:type" content="article"/>
<meta property="og:url" content="<?php echo get_permalink(); ?>"/>
<meta property="og:site_name" content="<?php echo get_bloginfo(); ?>"/>
<meta property="og:image" content="<?php echo $img_src; ?>"/>
<?php
}
add_action('wp_head', 'fb_opengraph', 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment