Today, I’ll show you how you can add a Facebook Like button in WordPress without using a plugin.
To show the Facebook Like button below your posts, all we need to do is create a function and add a filter to the $content variable.
Open your theme functions.php file and add :
function facebook_like_button ($content) {
if (is_single()) {
$content .= '<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink($post->ID)); ?>&layout=button_count&show_faces=false&width=450&action=like&colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:110px; height:30px;"></iframe>';
}
return $content;
}
add_filter( "the_content", "facebook_like_button");
To style the button differently, you will need to modify the “layout=” section.
Valid styles are “standard”, “button_count” and “box_count”. You may also need to adjust the “width” and “height” sections for the other styles to display correctly.
When adding the “like” button to your blog, It’s also important to include the Facebook meta tags. These meta tags allows you to control exactly how your post will appear on the users Facebook wall page.
Open your theme functions.php file and add :
function facebook_meta_tags_posts() {
if (is_single()) {
global $post;
$content = $post->post_content;
$images = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$image = $matches [1] [0];
if (!$image)
{
$image = 'HTTP://YOUR DEFAULT IMAGE LOCATION HERE';
}
?>
<meta property="og:title" content="<?php the_title(); ?>"/>
<meta property="og:description" content="<?php echo get_post_meta($post->ID, 'thesis_description', true) ?>"/>
<meta property="og:url" content="<?php the_permalink(); ?>"/>
<meta property="og:image" content="<?php echo $image; ?>"/>
<meta property="og:type" content="article"/>
<meta property="og:site_name" content="<?php bloginfo('name'); ?>"/>
<?php
}
}
add_action('wp_head', 'facebook_meta_tags_posts');
Not only will this function automatically create all the necessary meta tags for you, it will also add your post image (if one is present) to display on the users Facebook wall.
If an image is not present, it will use the image (that you defined) in the “HTTP://YOUR DEFAULT IMAGE LOCATION HERE” section.
Feel free to share your thoughts in the comments section below!