The other day I mentioned a ‘solution’ to my problem of video enclosures would also be to use a JSON feed. As much as I’d like to tell you just to use JSON feed, you can’t because their specs don’t match Amazon’s.

The creation of a JSON Feed that does match their specs is somewhat peculiar, but still straightforward. I went with making a JSON API output instead of making true feed, since frankly I don’t think Amazon’s all that consistent with their own spec, and I’ll need to tweak it later. I’d like to do so without breaking everything else.

The Code

class MYSITE_Alexa_Skills {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'rest_api_init') );
	}

	/**
	 * Rest API init
	 *
	 * Creates callbacks
	 *   - /MYSITE/v1/alexa-skills/briefing
	 */
	public function rest_api_init() {

		// Skills
		register_rest_route( 'MYSITE/v1', '/alexa-skills/briefing/', array(
			'methods' => 'GET',
			'callback' => array( $this, 'flash_briefing_rest_api_callback' ),
		) );
	}

	/**
	 * Rest API Callback for Flash Briefing
	 */
	public function flash_briefing_rest_api_callback( $data ) {
		$response = $this->flash_briefing();
		return $response;
	}

	/**
	 * Generate the Flash Briefing output
	 */
	public function flash_briefing() {
		$query = new WP_Query( array( 'numberposts' => '10' ) );
		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) {
				$query->the_post();

				$response = array(
					'uid'            => get_the_permalink(),
					'updateDate'     => get_post_modified_time( 'Y-m-d\TH:i:s.\0\Z' ),
					'titleText'      => get_the_title(),
					'mainText'       => get_the_excerpt(),
					'redirectionUrl' => home_url(),
				);

				$responses[] = $response;
			}
			wp_reset_postdata();
		}

		if ( count( $responses ) === 1 ) $responses = $responses[0];

		return $responses;
	}
}
new MYSITE_Alexa_Skills();

Some Notes…

This is built out with the assumption I will later be adding more information and skills to this site. That’s why the class is named for the skills in general and has the rest route set up for sub-routines already. If that’s not on your to-do, you can simplify.

I also made the point to strip out the possibility of a StreamURL, which I don’t plan to use at all on this site. If you do, I recommend having a look at VoiceWP’s briefing.php file which does a nice job with handling that.

Reader Interactions

%d bloggers like this: