How to Add Post Categories and Tags as #Hashtags to Tweets Automatically with the Simple Twitter Connect Plugin

Simple Twitter Connect is a really useful, simple and well coded plugin by Otto (@Otto42) that allows you to post tweets right from your WordPress dashboard or automatically after publishing new posts.

A standard tweet containing a prefix (such as “New blog post:”), post title and a link to that post is generated automatically by the plugin. Wouldn’t it be nice to include also post categories and tags as hashtags in order to add additional metadata along with the post title? Like so:

Post categories and tags added as hashtags in Twitter Publisher using Simple Twitter Connect plugin

Post categories and tags replaced or added to tweet as hashtags

Thanks to the stc_publish_text filter supplied with the plugin there is an easy way to do it. Add this snippet to your theme’s functions.php:

add_filter('stc_publish_text', 'add_taxonomies_to_tweets', 10, 2);

function add_taxonomies_to_tweets($output, $id) {
	if ($cats = get_the_category($id))
		foreach ($cats as $c => $cat)
			$output = add_taxonomy_hashtag($output, $cat->cat_name);

	if ($tags = get_the_tags($id))
		foreach ($tags as $t => $tag)
			$output = add_taxonomy_hashtag($output, $tag->name);

	return $output;
}

function add_taxonomy_hashtag($tweet, $tax) {
	if (stripos($tax, ' ')) // Remove whitespace
		$tax = str_replace(' ', '', $tax);

	if (strlen($tweet) + 1 > 140) { // Check if the new tweet is not too long
		return $tweet;
	} elseif (stripos($tweet, $tax)) {  // Replace an existing word with a tag
		return str_replace($tax, '#' . $tax, $tweet);
	} elseif (strlen($tweet) + strlen($tax) + 1 < 140) { // or simply append it
		return $tweet . ' #' . $tax;
	}

	return $tweet;
}

Leave a Reply