janboddez / share-on-mastodon

Easily share WordPress posts on Mastodon.
https://jan.boddez.net/wordpress/share-on-mastodon
GNU General Public License v3.0
39 stars 5 forks source link

Add author to Mastodon post #78

Closed Morid1n closed 1 year ago

Morid1n commented 1 year ago

We have a Wordpress install with multiple authors. I'd like to be able to post to Mastodon something akin to:

This is the title of the post

by @author@instance.com

https://link.to.the.post.com

We're using the Advanced Custom Fields plugin to add these fields to a users profile, so they can list all of their social media accounts which WP doesn't account for.

An example of the SoMe section of a user's profile:

image
janboddez commented 1 year ago

Hi, you can try adding a share_on_mastodon_status filter: https://jan.boddez.net/wordpress/share-on-mastodon#share_on_mastodon_status

Example code for use with ACF's user fields (off the top of my head, untested!):

add_filter( 'share_on_mastodon_status', function( $status, $post ) {
  $status = get_the_title( $post ); // Start with the title.

  if ( function_exists( 'get_field' ) ) {
    // If ACF is active, grab the post author's Mastodon URL.
    $author = get_field( 'the-name-of-your-mastodon-field', 'user_' . $post->post_author ); // Fill out your field name.
  }

  if ( ! empty( $author ) ) {
    // Now convert this URL into `@name@instance.tld`!
    $author  = basename( $author ) . '@' . wp_parse_url( $author, PHP_URL_HOST ); // Or something.
    $status .= "\n\nby " . $author;
  }

  $status .= "\n\n" . get_permalink( $post ); // Add the backlink.
  $status  = html_entity_decode( $status, ENT_QUOTES | ENT_HTML5, get_bloginfo( 'charset' ) ); // Or similar, to avoid double-encoded HTML entities.

  return $status;
}, 10, 2 );

You'd add that in a mu-plugin, your child theme's functions.php or through a "PHP snippets" plugin.