Skip to content

Using “Share on Mastodon” to Cross-Post Audio or Video

Share on Mastodon, for those not in the know, is a WordPress plugin that lets you automatically “share” new posts on Mastodon. By default, it posts a title and permalink, but it can be set up to cross-post excerpts, too—or pretty much everything.

It’ll also upload the post’s featured and attached images; up to 4 images are supported, a hard limit imposed by Mastodon. (This behavior is easily disabled, though.)

The plugin’s latest version (0.12.1) comes with a share_on_mastodon_media hook, which lets developers filter the array of attachment IDs to be uploaded to Mastodon.

As said, by default, it will only pick up images, but we can add a filter callback and choose to upload audio or video instead.

Here’s one example:

<?php

add_filter( 'share_on_mastodon_media', function( $media, $post ) {
  $video = get_attached_media( 'video', $post->ID );

  if ( empty( $video ) ) {
    // Current post doesn't have any video attached to it.
    return $media;
  }

  // Grab the first video attachment.
  $video = reset( $video );

  // Return up to three images plus our one video file.
  return array_merge( array_slice( $media, 0, 3 ), array( $video->ID ) );
}, 10, 2 );

In this particular case, we limit the number of images to three—fewer images are okay, too—and then add the post’s first attached video file. (An attached media file is a file uploaded through the Create or Edit Post screens, for that particular post, no matter if the file is present in the actual post. Files directly uploaded to the media library will likely not work.)

To cross-post audio, simply use get_attached_media( 'audio', $post->ID ); instead. Note that files should not be larger than 40 MB—the limit for images is 8 MB—and that their file type must be supported by Mastodon.

There’s a few additional risks, too, like … your web server might time out halfway the request to Mastodon’s API, and so on. Not sure how likely that is.

In case you wanted to try it out yourself, I created this gist (which can be used as an actual “mu-plugin”).

Replies

  1. cagrimmett.com on

    … liked this!