Automatically Share WordPress Posts on Mastodon

Since Mastodon is really taking off (this time around), I was thinking about how to use it and integrate it into my general publishing workflow. (Not that I am posting much, but still.)

I have always been a fan of posting to my blog first, then to social media second.

A couple of days ago I activated post formats, more precisely the “status” format, to publish short notes, which do not warrant a proper blog post.

I also wanted to share those notes on Mastodon automatically. When looking into how to achieve that, I found the Share on Mastodon plugin. It is pretty straight forward to configure and it just works.

Jan, the developer, has added some well placed filters, which you can use to define exactly what is being shared. Have a look at the documentation with some examples on Jan’s website.

I made some adjustments using the share_on_mastodon_status filter, so that the post on Mastodon contains different things depending on the post format:

add_filter( 'share_on_mastodon_status', function( $status, $post ) {

    // Share only the post content if it is a status post
    if ( has_post_format( 'status', $post ) ) {
        $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;

}, 10, 2 );

Let’s connect on Mastodon!