Post from WordPress to Mastodon

I always liked the idea of having your content, even those short social posts or status updates, on your own website and then shared to social media, but never got around to implement something like it. After using mastodon for a few weeks now (and this time it feels like it’ll take off for real), and after reading Florian’s post about how he set up his site to automatically post to mastodon, I thought I could do something similar.

Most of what I did so far is stolen from what Florian did. The only difference is that I use a category instead of a post-format for my “notes” ā€“ maybe I even switch to a custom post type later on. Also, I wanted to exclude my (almost) weekly reading lists (which are a post category for now as well) from auto-sharing, for now at least.

Altogether, here’s the code to make the shared posts look different depending on the post category. The only difference to Florian’s Snippet is in the three lines I highlighted, which check for the category.

**
 * Customize Posts for Mastodon Sharing
 */
function claudio_customize_mastodon_post( $status, $post ) {

	// Share only the post content if it is in category "note"
	if ( has_category( 'notes') ) {
		$status = wp_strip_all_tags( $post->post_content );
	}
	// Share title + tags + url, if it is a regular post
	else {
		$status = wp_strip_all_tags( get_the_title( $post->ID ) );
		$tags = get_the_tags( $post->ID );
		if ( $tags ) {
			$temp = '';
			foreach( $tags as $tag ) {
				$temp .= '#' . preg_replace( '/\s/', '', $tag->name ) . ' ';
			}
			$status .= "\n\n" . trim( $temp );
		}
		$status .= "\n\nšŸ”— " . get_the_permalink( $post->ID );
	}

	return $status;

}
add_filter( 'share_on_mastodon_status', 'claudio_customize_mastodon_post', 10, 2 );
Code language: PHP (php)

And here’s how I exclude the category “reading-list” from auto-posting:

/**
 * Don't share reading lists on mastodon for now
 */
function claudio_exclude_reading_lists_from_mastodon( $is_enabled, $post_id ) {
	if ( has_category( 'reading-list', $post_id ) ) {
		return false;
	}

	return $is_enabled;
}
add_filter( 'share_on_mastodon_enabled', 'claudio_exclude_reading_lists_from_mastodon', 10, 2 );Code language: PHP (php)

Next up: As I’m not sure if I will jump ship on twitter completely for now, I guess the next step would be to search for a solution that works the same way, to share those notes on twitter as well.

Made with ā¤ļø in Switzerland