Add hashtags support to WordTwit

This is a development of this article written in 2009.

How to re-use the tags added to an article in WordPress as Twitter hashtags? With some modifications to WordTwit, it's possible. Here's how.

The modification involves editing the file wordtwit.php, which can be found in your /wp-content/plugin/wordtwit/ directory. The first part is very minor and simply involves moving a line of code a little further up. You need to look for "$post_tags = get_the_tags();" near line 882 in version 2.5.1 of WordTwit (line 950 in 2.6):

$new_taxonomy = array();

$post_tags = get_the_tags();
if ( $post_tags ) {
foreach ( $post_tags as $some_tag ) {
$new_taxonomy[] = strtolower( $some_tag->name );
}
}

Move the  "$post_tags = get_the_tags();" line up and place it under the "$can_tweet = true;" line. This is done to avoid calling the same function twice. So now the above code will look like this:

$can_tweet = true;
$post_tags = get_the_tags();

// check tags
if ( count( $wt_tags ) ) {

// we have a tag or a category
$new_taxonomy = array();

if ( $post_tags ) {
foreach ( $post_tags as $some_tag ) {
$new_taxonomy[] = strtolower( $some_tag->name );
}
}

Next, inside the wordtwit_get_message() function after $message = str_replace( '[title]', $my_post->post_title, $message ); you need to inject the code that will handle the WordPress tags to Twitter hashtag conversion:

// !!! WordPress tag to Twitter hashtag conversion STARTS HERE >>>
if ( $post_tags && strpos($message, '[tags]') !== false ) {
$tags_to_add = ";
// What's the message length without this tag?
$message_len = strlen($message) – 6;
foreach ( $post_tags as $some_tag ) {
$tag_len = strlen($some_tag->name) + 2;
// Can we add this tag within the 140 char constraint? (accounts for hashtag and spacer)
if ( $tag_len + $message_len <= 140 ) {
$tags_to_add .= '#'.$some_tag->name.' ';
$message_len += $tag_len;
}
}
$tags_to_add = rtrim($tags_to_add);
$message = str_replace('[tags]', $tags_to_add, $message);
}
// <<< WordPress tag to Twitter hashtag conversion ENDS HERE !!!

Then addition to this I added these bits of code too:

At the top of function wordtwit_get_message() and wordtwit_post_now_published() add this:

global $post_tags;

Finally, to get this to work you need to edit the plugin settings in wp-admin. Under Account Login/Message Tweet you need to include [tags] in the message field (e.g. [title] – [link] [tags])

About Keiron

Web Developer based in the UK. Click here if you want to work with me