Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Last active January 29, 2021 01:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wpscholar/68185d59d9c930123f6ecbe7628c87a0 to your computer and use it in GitHub Desktop.
Save wpscholar/68185d59d9c930123f6ecbe7628c87a0 to your computer and use it in GitHub Desktop.
A simple must-use plugin for WordPress that will provide a `/feed/json` endpoint for converting RSS feeds to JSON.
<?php
/**
* A simple must-use plugin for WordPress that will provide a `/feed/json` endpoint for converting RSS feeds to JSON.
* In the absence of any URL parameters, it will convert the main feed to JSON. If a URL is set, it will convert the
* feed from that URL into JSON. If a callback is set, a JSONP implementation will be returned.
*
* Note: Be sure to flush rewrite rules manually by visiting the 'General'->'Permalinks' page in the WordPress admin. If
* you are using this in a plugin, be sure to flush the rewrite rules on activation using the 'flush_rewrite_rules()' function.
*
* @author Micah Wood <micah@wpscholar.com>
*/
add_action( 'init', function () {
add_rewrite_endpoint( 'feed', EP_ROOT );
} );
add_action( 'template_redirect', function () {
if ( 'json' === get_query_var( 'feed' ) ) {
$jsonp = filter_input( INPUT_GET, 'callback', FILTER_SANITIZE_STRING );
$url = filter_input( INPUT_GET, 'url', FILTER_SANITIZE_URL );
if ( empty( $jsonp ) && empty( $url ) ) {
$url = home_url( '/feed/' );
}
$request = wp_safe_remote_get( $url );
$response = array( 'success' => false, 'data' => (object) array() );
try {
if ( 200 !== wp_remote_retrieve_response_code( $request ) ) {
throw new Exception( 'Unable to fetch feed.' );
}
$xml = new SimpleXMLElement( wp_remote_retrieve_body( $request ), LIBXML_NOCDATA );
$response['success'] = true;
$response['data'] = $xml->channel;
} catch ( Exception $e ) {
$response['data']->message = $e->getMessage();
}
if ( $jsonp ) {
@header( 'Content-Type: application/javascript; charset=' . get_option( 'blog_charset' ) );
echo $jsonp . '(' . wp_json_encode( $response ) . ');';
die;
}
wp_send_json( $response );
}
} );
@wpscholar
Copy link
Author

wpscholar commented Nov 7, 2016

Sample usage (same domain): http://{yourDomain}/feed/json/?url={feedUrl}
Sample usage (cross domain): http://{yourDomain}/feed/json/?url={feedUrl}&callback={jsonpCallback}

@wpscholar
Copy link
Author

Sample JSONP implementation:

var url = 'http://{yourDomain}/feed/json/?url={feedUrl}&callback=rss';
var jsonp = document.createElement('script');
jsonp.src = url;
document.body.appendChild(jsonp);

function rss(data) {
    console.log(data);
}

@awsomedesigner
Copy link

How i can install into my website?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment