Get latest articles:

How to show social media buttons only on selected posts

Integrating social media icons (Digg, Delicious, StumbleUpon etc.) using plugins or theme hacks is a popular practice. There are different styles of adding the links, from beautiful icons to plain old text links and drop menus.

Here’s a recent spinoff that I experimented with – adding social media links/badges only on posts where you need to. The display of the Digg buttons will be controlled by a custom field. Note that no code for the social media links have been provided – you can use plugins or your favorite hacks for the purpose. The purpose of this tutorial is to help you check and use custom fields, not use social media links themselves.

In fact, I use the same method to selectively show Tweetmeme badges on posts that are likely to go viral on Twitter.

Using custom fields in your theme

WordPress’ custom fields can be grabbed with the get_post_meta() function.

$check_sm = get_post_meta($post->ID, 'sm', $single = true);
if($check_sm != '')
{
     // Links here
}

In the above code, the custom field named sm is assigned to a variable check_sm for ease of use. We check whether the custom field is not empty, if so, display the social media links. Enter your plugin function call or HTML code for links where it says Links here. You would probably want to use this hack on index and single pages.

Enabling social media links in posts

Use custom fields to show social media links only on some postsTo enable social media links for a particular post, scroll down to the custom fields section. Add a new custom field with the name sm, and give it the value true.

You can give any value for the key, because in the code above, to display links, we check only if there is some value assigned to the custom field. However, it’d be good practice to use a standard key (true) so that we account for the future (if you need ‘true’ in a future hack, for example).

Comments are closed.