Skip to content

Instantly share code, notes, and snippets.

@stefangrund
Created August 20, 2014 08:18
Show Gist options
  • Save stefangrund/f60da1c5d784530feacf to your computer and use it in GitHub Desktop.
Save stefangrund/f60da1c5d784530feacf to your computer and use it in GitHub Desktop.
This is the OpenGraph and Twitter Card implementation for my WordPress blog (http://eay.cc/) to display nice previews and pictures in Facebook and Twitter.
<?php
//Get first image in post
function firstImage() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$content = do_shortcode( $post->post_content );
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "http://eay.cc/uploads/default_eay.png";
}
return $first_img;
}
?>
<?php if (have_posts()):while(have_posts()):the_post(); endwhile; endif;?>
<meta property="fb:admins" content="1054296245">
<meta property="twitter:card" content="summary">
<meta property="twitter:site" content="@eaybot">
<meta property="twitter:creator" content="@eay">
<meta property="twitter:domain" content="eay.cc">
<?php if (is_single() OR is_page()) { ?>
<meta property="twitter:title" content="<?php single_post_title(''); ?>">
<meta property="twitter:description" content="<?php echo strip_tags(get_the_excerpt($post->ID)); ?>">
<meta property="twitter:image:src" content="<?php echo firstImage(); ?>">
<meta property="og:url" content="<?php the_permalink() ?>"/>
<meta property="og:title" content="<?php single_post_title(''); ?>">
<meta property="og:description" content="<?php echo strip_tags(get_the_excerpt($post->ID)); ?>" />
<meta property="og:type" content="article">
<meta property="og:image" content="<?php echo firstImage(); ?>">
<?php } else { ?>
<meta property="twitter:title" content="<?php bloginfo('name'); ?> – Weblog von Stefan Grund">
<meta property="twitter:description" content="Das Weblog von Stefan Grund, der im Netz als @eay unterwegs ist und hier seit 2003 über Popkultur, Medien und Technologie schreibt.">
<meta property="twitter:image:src" content="http://eay.cc/uploads/default_eay.png">
<meta property="og:site_name" content="<?php bloginfo('name'); ?> – Weblog von Stefan Grund">
<meta property="og:description" content="Das Weblog von Stefan Grund, der im Netz als @eay unterwegs ist und hier seit 2003 über Popkultur, Medien und Technologie schreibt.">
<meta property="og:type" content="website">
<meta property="og:image" content="http://eay.cc/uploads/default_eay.png">
<?php } ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment