How to Detect Multiple Matterport URLs and Embed Them Automatically

on in Blog
Last modified on

Embedding a Matterport tour in a WordPress page proves to be a bit problematic using the regular link-to-oEmbed method. There’s countless console errors, CORS errors and so on. So I did it programmatically.

Considering this tour URL:

https://my.matterport.com/show/?m=JB3xJG3JkVB

I created a regular expression:

/(?:https?:\/\/)?(?:(?:(?:my\.?)?matterport\.com\/show\/\?m=([0-9a-zA-Z]+)+))/i

Here’s the live playground – https://regexr.com/5g6m6

Then, in my theme, I replaced the URL with the official iframe embed code. Note that I have a separate function to display this and to add more filters and hooks, but, in order to illustrate the Matterport issue, I have only kept the relevant code:

/**
 * Display the content
 *
 * @param int $postId Post ID.
 */
function wppd_post_content($postId) {
    $postContent = get_the_content($postId);

    // Apply content filters such as Matterport embeds
    $postContent = preg_replace('%(?:https?:\/\/)?(?:(?:(?:my\.?)?matterport\.com\/show\/\?m=([0-9a-zA-Z]+)+))%i', "<p><iframe id='showcase-player' width='853' height='480' src='https://my.matterport.com/show/?m=$1' frameborder='0' allowfullscreen='' allow='xr-spatial-tracking' style='width: 100%;'></iframe></p>", $propertyDescription);

    // Apply content filters such as YouTube embeds
    $postContent = apply_filters('the_content', $postContent);

    return $postContent;
}

Related posts