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

Filter function to format your toots better #52

Closed adegans closed 1 year ago

adegans commented 1 year ago

https://ajdg.solutions/blog/format-your-toots-on-mastodon-when-using-share-on-mastodon/

Over the past few days I’ve been making test posts and settled on a format for toots like so: https://home.social/@arnandegans/109684410554812887. Clean, simple, easy to read.

If you want this layout as well, add the following code to your themes functions.php file.

// Reformat the toot format/template for Share to Mastodon
function ajdg_share_on_mastodon($status, $post) {
    $formatted_status  = wp_strip_all_tags(html_entity_decode(get_the_title($post->ID), ENT_QUOTES | ENT_HTML5, get_bloginfo('charset'))) . "\n\n";
    $formatted_status .= mb_substr(wp_strip_all_tags(html_entity_decode(get_the_excerpt($post->ID))), 0, 199, get_bloginfo('charset')) . "[…]\n";
    $formatted_status .= esc_url_raw(get_permalink($post->ID)) . "\n\n";

    $toot_tags = get_the_tags($post->ID);
    if($toot_tags) {
        foreach($toot_tags as $tag) {
            $tags[] = "#" . preg_replace("/[^a-z0-9]/i", '', $tag->name);
        }
        $formatted_status .= implode(" ", $tags);
        unset($tags, $toot_tags);
    }

    return $formatted_status;
}
add_filter( 'share_on_mastodon_status', 'ajdg_share_on_mastodon', 10, 2);

This basically does the same as the plugin does by default. But adds the except of the post (or a snippet if the excerpt doesn’t exist) and adds the tags. Tags with spaces do not work on Mastodon, so spaces are stripped out. And a few new lines are added for readability.

janboddez commented 1 year ago

Yep, there's a lot you can do. Even more inspiration in this thread: https://github.com/janboddez/share-on-mastodon/issues/37#issuecomment-1362543150