-
-
Save alinademi/413ce300e3742fca010a5d0016c0b6da 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 ); | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment