Control how Facebook likes & Tweeted URLs look from WordPress

If you want to control what image and content Facebook uses when someone likes a post/page on your WordPress site, then add this snippet to your theme functions.php. Any Facebook likes will then use the featured image from that post or page.

A similar thing can be done with Twitter – called Twitter cards – a simple version is previewed below. It can add a neat little card under a tweeted url from your site if you use the code below and apply to the program! It takes 5-10 days to be improved, so do it now!

twitter-card-preview

How to get it working
1) Use the code below in your theme and get it uploaded
2) Go to https://dev.twitter.com/docs/cards/preview to check it works with a url from your site with my code!
3) Go to https://dev.twitter.com/form/participate-twitter-cards to apply.

[code]add_action( ‘wp_head’, my_theme_facebook_meta_tags );
function my_theme_facebook_meta_tags()
{
global $post;
echo'<!–Facebook tags–>’;
//image
if(function_exists( ‘has_post_thumbnail’ )&& has_post_thumbnail( $post->ID ))
{
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), ‘thumbnail’ );
echo'<meta property=”og:image” content=”‘.$thumb[0].'”/>’;
}
elseif(function_exists(header_image))
{
$thumb=header_image();
if(!empty($thumb)) echo'<meta property=”og:image” content=”‘.$thumb.'”/>’;
}
//url
echo'<meta property=”og:url” content=”‘.get_permalink($post->ID).'”/>’;
//post title
echo'<meta property=”og:title” content=”‘.get_the_title() .'”/>’;
//site name
echo'<meta property=”og:site_name” content=”‘.get_bloginfo(‘name’).'”/>’;
//excerpt
if ( !empty($post->post_excerpt) ) {
$description = strip_tags(strip_shortcodes($post->post_excerpt));
}
else
{
$description = my_theme_wordlimit(strip_tags(strip_shortcodes($post->post_content)));
}
echo ‘<meta property=”og:description” content=”‘.$description.'”/>’;
echo'<!–End Facebook tags–>’;
}
function my_theme_wordlimit($string, $length = 50, $ellipsis = “…”)
{

$words = explode(‘ ‘, $string);
if (count($words) > $length)
return implode(‘ ‘, array_slice($words, 0, $length)) . $ellipsis;
else
return $string;
}[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *