placeholders, which Zaraz replaces with the post on Cloudflare, so the * visitor's browser loads no Instagram script and Instagram sets no cookies. Works through the * [zbridge_instagram url="..."] shortcode and by pasting an Instagram post or reel link on its * own line (or into an Embed block). */ class InstagramEmbeds { /** * Instagram post, reel and IGTV links. */ public const URL_PATTERN = '#^https?://(?:www\.)?instagram\.com/(p|reel|tv)/([A-Za-z0-9_-]+)/?(?:[?\#].*)?$#i'; /** * Registers the shortcode and the pasted-link handler when Instagram embeds are enabled. */ public function register(): void { if (!Options::get('instagram_embeds', false)) { return; } add_shortcode('zbridge_instagram', [$this, 'shortcode']); wp_embed_register_handler('zbridge_instagram', self::URL_PATTERN, [$this, 'embedHandler']); } /** * [zbridge_instagram url="https://www.instagram.com/p/..." captions="true"] * * @param array|string $atts * @return string */ public function shortcode($atts): string { $rawAtts = (array) $atts; $atts = shortcode_atts(['url' => '', 'captions' => 'false'], $rawAtts, 'zbridge_instagram'); $url = (string) $atts['url']; // If 'url' was corrupted (e.g. nested quotes from pasting an HTML tag), // recover the Instagram URL from any attribute fragment. if (self::canonicalUrl($url) === '') { foreach ($rawAtts as $val) { if (is_string($val) && preg_match('#https?://(?:www\.)?instagram\.com/(?:p|reel|tv)/[A-Za-z0-9_-]+#i', $val, $match)) { $url = $match[0]; break; } } } return $this->render($url, filter_var($atts['captions'], FILTER_VALIDATE_BOOLEAN)); } /** * Embed handler for pasted Instagram links. * * @param array $matches * @param array $attr * @param string $url * @param array $rawattr * @return string */ public function embedHandler($matches, $attr, $url, $rawattr): string { return $this->render((string) $url, false); } /** * The Zaraz placeholder, with a plain link inside for when Zaraz does not render the post. * * @param string $url * @param bool $captions * @return string */ public function render(string $url, bool $captions): string { $postUrl = self::canonicalUrl($url); if ($postUrl === '') { return ''; } return sprintf( '%3$s', esc_url($postUrl), $captions ? 'true' : 'false', esc_html__('View this post on Instagram', 'zbridge') ); } /** * https://www.instagram.com/{p|reel|tv}/{id}/ — the Zaraz component appends "embed/" to it. * * @param string $url * @return string Empty when the URL is not an Instagram post. */ public static function canonicalUrl(string $url): string { $url = trim(html_entity_decode(wp_strip_all_tags($url), ENT_QUOTES, 'UTF-8')); if (!preg_match(self::URL_PATTERN, $url, $m)) { if (preg_match('#https?://(?:www\.)?instagram\.com/(p|reel|tv)/([A-Za-z0-9_-]+)#i', $url, $m)) { return 'https://www.instagram.com/' . strtolower($m[1]) . '/' . $m[2] . '/'; } return ''; } return 'https://www.instagram.com/' . strtolower($m[1]) . '/' . $m[2] . '/'; } }