There are some great plugins out there for adding a tweet button to your site, but a very small amount of code can add this via your theme without the extra plugin. I used An Alternative Method for Adding a Tweet Button from the StudioPress Dev site as a starting point, but found it didn’t do everything I want. First, there was a small error that resulted in the button not validating. I prefer my code to validate when possible so I hunted down the issue with the help of the original author Gary Jones. The tutorial was updated with that fix.
I now had a functioning tweet button, but it still didn’t do everything I wanted. Plugins such as TweetMeme allow you to include your categories and tags as hashtags in your tweet. If you aren’t aware a hash tag can be added to a tweet to follow trends. Simply put a # before any word in a tweet and it becomes a hash tag. Then followers can click the created link to see other instances of the hash tag in the twitter stream.
I’m sure you can see where this could be useful, as a way of giving your followers a way to quickly bring up other tweets for your blog, and those terms, also for your to quickly see tweets using those hashtags, and as a way for people viewing that hashtag stream from another source to find your blog. So the problem is getting the tweet to integrate the terms as hashtags.
Here is the code that does the magic.
$termlist = ' #DesignsBy'; $title = get_the_title( $post->ID ); $terms = wp_get_object_terms( $post->ID, array( 'category', 'post_tag' ) ); foreach ( $terms as $term ) { if ( in_array( $term->slug, array( 'uncategorized', 'all' ) ) ) continue; if ( strlen( $title . str_replace( ' ', '', $term->name ) . $termlist ) >= 115 ) continue; $termlist .= ' #' . str_replace( ' ', '', $term->name ); }
The first line creates a variable and assigns my first hashtag. This is the most important one for my site so I make sure it gets added before building anything else. The second line gets the title. I am checking against that in the foreach so it is faster to get it once in the variable than to get it each time. The third line fetches an array of terms assigned to my object. I could have gone through a complicated foreach to account for all taxonomies, but I really only need the ones I’m using on this site, categories and post tags. One might add additional taxonomies to the list as needed or even skip the categories or tags.
Since wp_get_object_terms() returns an array I need to run a foreach() to add the term name to my string, which is my fifth line. After that I check to see if it is a category I want to skip. If I forgot to assign a category it will add “uncategorized” to my list and that’s not cool. I also have a category I use for organizing my site. I call it “all” and it isn’t really useful as a hashtag. This array can be adjusted to skip any terms that one might need to skip.
Twitter doesn’t allow more than 140 characters so I also have to run a check to see if the tweet will be too long, that’s what my 10th line does. Since I have “via @Nick_theGeek” added to the end and I want to leave a little bit of room I make sure the title and term list isn’t longer than 115 characters. If adding the new term will exceed that length then it “continues” which means it skips that term and checks to see if the next term will fit in the remaining space. I could have used “break” but if I have a long tag before a short tag then the short tag might fit still even if the long one won’t.
The line thirteen builds the actual string. The “.=” part means it just adds the new info onto the end of the existing string. I put my ” #” at the front of the hash I’m going to build and the remove any spaces in the term name since hashtags can’t have a space in them.
The only thing left is to put the new term list after the title.
// Default Tweet text - here, the post title 'text' => $title.$termlist,
Here is the complete code
add_action( 'wp_print_scripts', 'child_add_tweet_button' ); /** * Add tweet link and script. * * @author Gary Jones * @link http://dev.studiopress.com/alternative-tweet-button.htm */ function child_add_tweet_button() { // Only add this to anything not a page if ( !is_page() ) { // Add a script to the bottom of the source wp_enqueue_script( 'tweet-button', 'http://platform.twitter.com/widgets.js', array( ), '', true ); // Filter in the required Twitter link for limited and unlimited content add_filter( 'genesis_post_info', 'child_add_tweet_button_link' ); } } /** * Add tweet link. * * @author Gary Jones * @link http://dev.studiopress.com/alternative-tweet-button.htm * * @param string $content HTML markup for post content * @return string HTML markup for post content */ function child_add_tweet_button_link() { global $post; $termlist = ' #DesignsBy'; $title = get_the_title( $post->ID ); $terms = wp_get_object_terms( $post->ID, array( 'category', 'post_tag' ) ); foreach ( $terms as $term ) { if ( in_array( $term->slug, array( 'uncategorized', 'all' ) ) ) continue; if ( strlen( $title . str_replace( ' ', '', $term->name ) . $termlist ) >= 115 ) continue; $termlist .= ' #' . str_replace( ' ', '', $term->name ); } $query_string_parameters = array( // URL of the page to share 'url' => get_permalink(), // Screen name of the user to attribute the Tweet to 'via' => 'Nick_theGeek', // Default Tweet text - here, the post title 'text' => $title.$termlist, // Related accounts that will be suggested to follow once tweet has been shared 'related' => 'Nick_theGeek', // Count box position - 'horizontal', 'vertical' or 'none' 'count' => 'horizontal', // The language for the Tweet Button - default is English (en) 'lang' => 'en', // The URL to which your shared URL resolves to 'counturl' => get_permalink() ); // Optionally use this if you have custom shortlinks set up. Uncomment to use. //$query_string_parameters['url'] = wp_get_shortlink(); // Construct our URL to pass to Twitter - gets urlencoded here $twitter_url = add_query_arg( $query_string_parameters, '//twitter.com/share' ); //$twitter_url = str_replace( '&via', '?via', $twitter_url ); return '[post_date] by [post_author_posts_link] at [post_time] [post_comments] [post_edit] <a href="' . htmlspecialchars( $twitter_url ) . '" class="twitter-share-button">Tweet</a>'; }
You can see that I made a couple other small changes. I’m not adding my button into the content, but to the Post Info. This means I had to change the add_filter() and the final line.
You can see it in action here in the post info on my personal blog, My Experience As…, as an add_action instead of a filter. The last line has to be echoes instead of returned when added to an action hook.
Ryan says
I have applied this code to my site and it is working great, however, for some reason I cannot get the Tweet button to show up on my home page. I’ve built a child theme based on the Lifestyle 2.0 theme. Any suggestion on how to get it to display on the homepage in addition to single post pages?
Also, can you show how to add a Google+ and Facebook buttons to this?
nickthegeek says
I might put together another tutorial on working with Google + and FB Like, the code is pretty similar. As for Lifestyle 2.0, likely the issue is that the home page is widgeted. My Genesis Featured Widget Amplified could be adapted for this change, although the simplest solution would be to convert the Tweet Button into short code. That’s really a tutorial for another day too.
Paul Letourneau says
Thanks for this Nick.
I like the idea of turning all of this and Facebook/Google+ buttons into a short code. Could make life a lot easier for a lot of Genesis fans.
Nick - WiseBod says
Hey sorry I didnt see this earlier. This is better code than the WP Smith tutorial.
I have it working on my site, and see that you use float: right on the .twitter-share-button class in order to make it right aligned. So that is a big help to me.
Something I’m unsure about though. What is this line of code for, and what should I change it to?
$termlist = ‘ #DesignsBy’;
nickthegeek says
Yeah. I didn’t get into that line in detail. I like to have all the tweets from my blog with a common hash tag. That line adds in a hash to all the tweets from this button. You can change it to something specific to you site or just leave it empty with ”