Better sharing of WordPress posts to Mastodon
WordPress's Jetpack plugin allows you to easily syndicate your blog to Twitter, LinkedIn, Tumblr, Email, and a few other services. But there's no native way to publish directly to your Mastodon feed.
This is a guide to how I got my blog to publish every new post to Mastodon with a nicely formatted preview. This uses Jan's "Share on Mastodon" plugin which you'll need to install and configure.
Once you've followed these instructions, you'll get a share which has a headline, excerpt, link, hashtags, and images. Ready? Let's go!
What it looks like
Here's a sample post shared onto Mastodon.
The Code
Add this to your theme's functions.php
file.
PHPadd_filter( 'share_on_mastodon_status', function( $status, $post ) {
// Create a short preview of the post
$status = "New blogging from me!\n\n";
$status .= "\"" . get_the_title($post) . "\"\n\n";
$status .= get_the_excerpt($post);
// Remove the … forced by the excerpt and replace with the Unicode symbol
$status = html_entity_decode($status);
// Add a link
$status .= "\n\nRead more: " . get_permalink( $post );
// Add tags
$tags = get_the_tags( $post->ID );
if ( $tags ) {
$status .= "\n\n";
foreach ( $tags as $tag ) {
$status .= '#' . preg_replace( '/\s/', '', $tag->name ) . ' ';
}
}
$status = trim( $status );
return $status;
}, 10, 2 );
If you're familiar with PHP, the code shouldn't contain too many surprises. The only confusing thing for me was needing to replace the hard-coded …
with …
as otherwise Mastodon treats it literally.
So, install "Share on Mastodon" plugin and get hacking!
Chris Coyier said on chriscoyier.net:
This Article was mentioned on chriscoyier.net
Jan Boddez said on indieblocks.xyz:
This Article was mentioned on indieblocks.xyz
BK says:
I figured out this code to add the categories as well. Nothing fancy, but wanted to share. Perhaps you could add it in to your code.
// Add catogories $categories = get_the_category( $post->ID ); if ( $categories ) { $status .= "\n\n"; foreach ( $categories as $category ) { $status .= '#' . preg_replace( '/\s/', '', $category->name ) . ' '; } }
Thanks!
More comments on Mastodon.