REST API Post Embeds: alter API query based on custom shortcode parameter

in WordPress

I got an interesting question from @slotty7130 in the WordPress.org support forums today: they wanted to use the REST API Post Embeds plugin to display posts from one of their websites, but only in a specific language as defined in WPML.

If you’re not familiar with REST API Post Embeds, my plugin defines a shortcode that runs REST API queries for you, using the WP REST API or the WordPress.com REST API. The shortcode accepts several parameters, but I didn’t build in any language parameter, as none of the APIs support it by default. Luckily, it looks like someone already developed a plugin that adds a lang parameter to the WP API, to query for specific WPML posts.

All we have to do now is:

  1. Add a new parameter to my shortcode;
  2. If that parameter is set in the post editor, alter the WP REST API query to include that parameter.

The former can be achieved with the shortcode_atts_{$shortcode} filter. The latter can be done thanks to the jeherve_post_embed_query_url filter in my plugin.

/**
 * Add new lang parameter to the shortcode.
 *
 * Must be used with a plugin that will allow you to retrieve specific posts
 * from the WP REST API when you add the `lang` parameter. This plugin seems to do the trick:
 * https://wordpress.org/plugins/wp-rest-api-multilanguage-over-wmpl/
 *
 * @see https://wordpress.org/support/topic/retrieving-wmpl-posts
 *
 * @param array  $out       The output array of shortcode attributes.
 * @param array  $pairs     The supported attributes and their defaults.
 * @param array  $atts      The user defined shortcode attributes.
 * @param string $shortcode The shortcode name.
 */
function jeherve_rest_api_embeds_lang( $out, $pairs, $atts, $shortcode ) {

	if ( isset( $atts['lang'] ) && '' != $atts['lang'] ) {
		$out['lang'] = $atts['lang'];
	}

	return $out;
}
add_filter( 'shortcode_atts_jeherve_post_embed', 'jeherve_rest_api_embeds_lang', 10, 4 );

/**
 * Use the new shortcode parameter in the REST API Post Queries.
 */
function jeherve_rest_api_embed_lang_query( $url, $atts, $args ) {

	if (
		// If a lang parameter was added as a shortcode, and if it is not empty
		( isset( $atts['lang'] ) && '' != $atts['lang'] )
		// If we are doing a WP REST API query, not a WordPress.com REST API one
		&& ( isset( $atts['wpapi'] ) && true === $atts['wpapi'] )
	) {
		$url = add_query_arg(
			array( 'lang' => esc_attr( $atts['lang'] ) ),
			$url
		);
	}

	return $url;
}
add_filter( 'jeherve_post_embed_query_url', 'jeherve_rest_api_embed_lang_query', 11, 3 );

Et voilà! I must admit that extending existing plugins without touching the plugin code is one of my favourite pastimes ?

Comments are closed.