Combining WPML & ActivityPub

This is a screenshot showing the effects of the changes detailed in the blog post. Viewing the "Change subscribed languages for tips@vivaldi.com" dialog in Mastodon, one can see that now both Japanese and English are listed as available options to filter on.

“WPML” (WordPress MultiLingual) is a plugin for WordPress that allows for translation of posts, pages and templates in WordPress.

“ActivityPub (WordPress plugin)” is a plugin for WordPress that allows for fediverse integration of a WordPress site under the ActivityPub protocol.

Wouldn’t it be nice if the two could work together? Fortunately with just a tiny bit of code, they can do just that.

The problem

The ActivityPub protocol allows for tagging the language of posts. The ActivityPub WordPress plugin will by default simply tag all posts as being in the chosen language of the site. WPML adds per-post language tagging, but the ActivityPub plugin is unaware of this, so continues tagging posts with the site-wide language setting instead.

The result of this is that with some posts being published with the wrong language, the language filtering and machine translation features of other fediverse tools (eg. Mastodon) cannot do anything.

The solution

The fix is actually very simple, we just need to tell the ActivityPub plugin where to get the language info:

function wpml_custom_ap_language(string $lang, int $post_id, WP_Post $post): string {
	$language_details = apply_filters('wpml_post_language_details', NULL, $post_id);

	if (is_array($language_details) && isset($language_details['language_code'])) {
		$lang = $language_details['language_code'];
	}

	return $lang;
}
add_filter('activitypub_post_locale', 'wpml_custom_ap_language', 10, 3);

This hooks into the ActivityPub’s post locale hook and uses WPML’s recommended method to get the post language.

This was implemented yesterday for our vivaldi.com blog accounts. So going forward, posts from eg. @[email protected] should now be correctly language-tagged.

Note that this solution was based on a very similar use-case here: https://herve.bzh/20241008-8202/ – the difference being that in their case the WPML plugin was not involved – instead the author was using WordPress’s built-in tags to define the post language.

Comment