Categories
How To

Hashtag Your Jetpack with Custom Post Types

Want to put a hashtag on your Jetpack’d tweets? You can do it with a little magic.

The brunt of this code comes from Jeremy Herve, who was explaining to someone how to add Category hashtags prefixed to Jetpack Publicize tweets.

That is, someone wanted to take a category for a post (say ‘How To’) and convert that into a hashtag (say #howto).

I too wanted to do this, but like my weirdly related posts, I needed to do the following:

1) Get the tags
2) Check if the tag slug was the same as a post slug for a specific custom post type
3) Output the hashtag as all one-word, no spaces, no hyphens

Here’s The Code

No more explaining, here’s the code.

class Hashtag_Jetpack {

	public function __construct() {
		add_action( 'publish_post', array( $this, 'custom_message_save' ) );
	}

	public function publicize_hashtags() {
		$post = get_post();

		// If the post isn't empty AND it's a post (not a page etc), let's go!
		if ( ! empty( $post ) && 'post' === get_post_type( $post->ID ) ) {
			$post_tags = get_the_tags( $post->ID );
			if ( ! empty( $post_tags ) ) {
				// Create list of tags with hashtags in front of them
				$hash_tags = '';
				foreach ( $post_tags as $tag ) {
					// Limit this to shows only.
					$maybeshow = get_page_by_path( $tag->name, OBJECT, 'post_type_shows' );
					if ( $maybeshow->post_name === $tag->slug ) {
						// Change tag from this-name to thisname and slap a hashtag on it.
						$tag_name   = str_replace( '-', '', $tag->slug );
						$hash_tags .= ' #' . $tag_name;
					}
				}

				// Create our custom message
				$custom_message = 'New post! ' . get_the_title() . $hash_tags;
				update_post_meta( $post->ID, '_wpas_mess', $custom_message );
			}
		}
	}

	// Save that message
	public function custom_message_save() {
		add_action( 'save_post', array( $this, 'publicize_hashtags' ) );
	}

}

new Hashtag_Jetpack();

The only ‘catch’ you may stumble on is that I’m checking against the post type of post_type_shows – just change that as you need to.

Voila! Instant hashtags.

Oh and if you’re wondering why I didn’t put in a check for “Is Jetpack active…” the reason is that this is adding a post meta, and doesn’t actually depend on Jetpack being active at all. Will it ‘clutter up’ your database if Jetpack isn’t active? Yes. But it won’t break your site so it’s safe enough for me.