How to Add Facebook Like Button in selective WordPress Posts

58

We have written about how you can add facebook like button in WordPress posts. There are hundreds of plugins that lets you add the facebook like button at the bottom of each post. But sadly, there is not a single plugin that lets you display the like button on selective WordPress posts. In this article, we will utilize WordPress Custom fields to display the facebook like button in selective WordPress posts.

First open your single.php and find the loop (a code that looks similar to this):

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

In the loop query, let’s create a call to check for a custom field “fb-like”. You will do this by replacing the above code with the one below:

<?php if (have_posts()) : while (have_posts()) : the_post();  // check for Facebook Like on Single Page  $fblike = get_post_meta($post->ID, 'fb-like', $single = true);  ?>

Now anywhere within the loop, you will need to add the following code:

<?php // if there's a Facebook Like on Single Page  if($fblike !== '') { ?>  <iframe src="https://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink($post->ID)); ?>&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:450px; height:60px;"></iframe>  <?php } // end if statement  // if there's not a Facebook Like on Single Page  else { echo ''; } ?>

The code above is basically checking for the custom field “fb-like” through our get_post_meta hook. If this custom field is specified, then the facebook button will be displayed in your single posts. If not, then it will not display anything on that area.

So in any post that you want to display the Facebook Like Button, simply add the custom field with a Name “fb-like” and value “true”, and you are done.

This similar Custom Fields technique can be used for many things such as displaying a digg button on selective WordPress posts and others.

Social Media Auto Publish Powered By : XYZScripts.com