Skip to content

Instantly share code, notes, and snippets.

@lgellert
Last active February 27, 2017 05:17
Show Gist options
  • Save lgellert/3379fc50c10c53b991302ae7139d1ad9 to your computer and use it in GitHub Desktop.
Save lgellert/3379fc50c10c53b991302ae7139d1ad9 to your computer and use it in GitHub Desktop.
WordPress function for Facebook OG meta tags
<?php
// put this into your theme's functions.php file
// swap out the default image online 10
// build the facebook og meta tags based on defaults
// or if on a page or post, pull information off that object
function opengraph_tags() {
// defaults
$title = get_bloginfo('title');
$img_src = get_stylesheet_directory_uri() . '/images/your_default_image_here.jpg';
$excerpt = get_bloginfo('description');
// for non posts/pages, like /blog, just use the current URL
$permalink = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if(is_single() || is_page()) {
global $post;
setup_postdata( $post );
$title = get_the_title();
$permalink = get_the_permalink();
if (has_post_thumbnail($post->ID)) {
$img_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large')[0];
}
$excerpt = get_the_excerpt();
if ($excerpt) {
$excerpt = strip_tags($excerpt);
$excerpt = str_replace("", "'", $excerpt);
}
}
?>
<meta property="og:title" content="<?= $title; ?>"/>
<meta property="og:description" content="<?= $excerpt; ?>"/>
<meta property="og:type" content="article"/>
<meta property="og:url" content="<?= $permalink; ?>"/>
<meta property="og:site_name" content="<?= get_bloginfo(); ?>"/>
<meta property="og:image" content="<?= $img_src; ?>"/>
<?php
}
add_action('wp_head', 'opengraph_tags', 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment