When linking a word in WordPress and publishing it in the Fediverse via ActivityPub, those links are getting removed. But what if you want to keep the links?

When asked about this in a feature request at GitHub, @obenland came up with a pretty nice solution I want to share here, which does exactly what I wanted.

In the end, the following text in WordPress:

The quick brown fox jumps over the lazy dog

Becomes this in the Fediverse:

The quick brown fox (https://en.wikipedia.org/wiki/Fox) jumps over the lazy dog

I just needed to adjust the filter, since I’m using only the excerpt when sharing my post content in Settings > ActivityPub > Settings > Activities > Post content via [ap_excerpt] (in a legacy template system). Thus, I cannot use the suggested filter activitypub_the_content as in the original. I need to use the generic post_content and check manually whether the current request is an ActivityPub request.

This is the final code:

<?php
/**
 * Transform links behind text to text (link).
 *
 * @see		https://github.com/Automattic/wordpress-activitypub/issues/1859#issuecomment-3480894020
 *
 * @param	string	$content Current content
 * @return	string Updated content
 */
function plugin_format_activitypub_links_with_urls( string $content ): string {
	if ( ! \function_exists( 'Activitypub\is_activitypub_request' ) || ! \Activitypub\is_activitypub_request() ) {
		return $content;
	}

	$content = \preg_replace_callback(
		'/<a\s+([^>]*?)href=["\']([^"\']+)["\']([^>]*?)>(.*?)<\/a>/is',
		function( $matches ) {
			$href = $matches[2];
			$link_text = \wp_strip_all_tags( $matches[4] );

			if ( empty( $href ) || \strpos( $href, '#' ) === 0 ) {
				return $matches[0];
			}

			if ( $link_text === $href ) {
				return $matches[0];
			}

			return $link_text . ' (' . \esc_url( $href ) . ')';
		},
		$content
	);

	return $content;
}

\add_filter( 'post_content', 'plugin_format_activitypub_links_with_urls' );
Code language: PHP (php)

This does only affect content that is viewed by a Fediverse client, though. It does not alter the content when embedding a post in another post on another page or similar.

Reposts

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn more about webmentions)