Last active
January 29, 2021 01:41
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 <[email protected]> | |
*/ | |
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 ); | |
} | |
} ); |
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);
}
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
Sample usage (same domain):
http://{yourDomain}/feed/json/?url={feedUrl}
Sample usage (cross domain):
http://{yourDomain}/feed/json/?url={feedUrl}&callback={jsonpCallback}