From bda594ec8688d3546c4ef973eeebdbaf0a05bd44 Mon Sep 17 00:00:00 2001
From: Erick Hitter <git-contrib@ethitter.com>
Date: Sun, 17 Jul 2022 16:19:37 -0700
Subject: [PATCH] Add shortcode

---
 inc/class-plugin.php | 50 ++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 48 insertions(+), 2 deletions(-)

diff --git a/inc/class-plugin.php b/inc/class-plugin.php
index 573c7d6..aa276f4 100644
--- a/inc/class-plugin.php
+++ b/inc/class-plugin.php
@@ -32,6 +32,13 @@ class Plugin {
 	 */
 	private const EPISODE_ID_PLACEHOLDER = '__EPISODE_ID__';
 
+	/**
+	 * Shortcode tag.
+	 *
+	 * @var string
+	 */
+	private const SHORTCODE_TAG = 'eth_anchor_fm';
+
 	/**
 	 * Singleton.
 	 *
@@ -67,14 +74,13 @@ class Plugin {
 	 */
 	private function _setup(): void {
 		add_action( 'init', [ $this, 'action_init' ] );
+
 		add_filter(
 			'oembed_fetch_url',
 			[ $this, 'filter_oembed_fetch_url' ],
 			10,
 			3
 		);
-
-		// TODO: add shortcode.
 	}
 
 	/**
@@ -88,6 +94,11 @@ class Plugin {
 			self::OEMBED_ENDPOINT,
 			true
 		);
+
+		add_shortcode(
+			self::SHORTCODE_TAG,
+			[ $this, 'do_shortcode' ]
+		);
 	}
 
 	/**
@@ -137,4 +148,39 @@ class Plugin {
 
 		return $provider;
 	}
+
+	/**
+	 * Render Anchor.fm iframe embed via a shortcode.
+	 *
+	 * @param array $attrs Shortcode attributes.
+	 * @return string
+	 */
+	public function do_shortcode( array $attrs ): string {
+		$attrs = shortcode_atts(
+			[
+				'src'    => null,
+				'url'    => null,
+				'width'  => '400px',
+				'height' => '102px'
+			],
+			$attrs,
+			self::SHORTCODE_TAG
+		);
+
+		// Fallback in case one passes `url` rather than `src`.
+		if ( empty( $attrs['src'] ) && ! empty( $attrs['url'] ) ) {
+			$attrs['src'] = $attrs['url'];
+		}
+
+		if ( empty( $attrs['src'] ) ) {
+			return '';
+		}
+
+		return sprintf(
+			'<iframe src="%1$s" width="%2$s" height="%3$s" frameborder="0" scrolling="no"></iframe>',
+			esc_url( $attrs['src'] ),
+			esc_attr( $attrs['width'] ),
+			esc_attr( $attrs['height'] )
+		);
+	}
 }
-- 
GitLab