-
-
Save mpalpha/14c467ce9356eb3d3a91fcd17dcf90c6 to your computer and use it in GitHub Desktop.
This file contains 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 | |
/* | |
Plugin Name: WordPress serves JSON | |
Description: Serve your content as JSON or JSONP in a simple manner (based on an example by Jon Cave - http://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints-api/). | |
Plugin URI: https://gist.github.com/lloc/8933914 | |
Author: realloc | |
Author URI: http://lloc.de/ | |
*/ | |
namespace LLOC\realloc; | |
function add_rewrite_endpoint() { | |
add_rewrite_endpoint( 'json', EP_PERMALINK | EP_PAGES ); | |
} | |
add_action( 'init', __NAMESPACE__ . '\\add_rewrite_endpoint' ); | |
function template_redirect() { | |
global $wp_query; | |
if ( ! isset( $wp_query->query_vars['json'] ) || ! is_singular() ) | |
return; | |
header( 'Content-Type: application/json' ); | |
$post = get_queried_object(); | |
if ( get_query_var( 'callback' ) ) { | |
echo get_query_var( 'callback' ) . '(' . json_encode( $post ) . ')'; | |
} | |
else { | |
echo json_encode( $post ); | |
} | |
exit; | |
} | |
add_action( 'template_redirect', __NAMESPACE__ . '\\template_redirect' ); | |
function add_query_var( $vars ){ | |
$vars[] = 'callback'; | |
return $vars; | |
} | |
add_filter( 'query_vars', __NAMESPACE__ . '\\add_query_var' ); | |
function endpoints_activate() { | |
add_rewrite_endpoint(); | |
flush_rewrite_rules(); | |
} | |
register_activation_hook( __FILE__, __NAMESPACE__ . '\\endpoints_activate' ); | |
function endpoints_deactivate() { | |
flush_rewrite_rules(); | |
} | |
register_deactivation_hook( __FILE__, __NAMESPACE__ . '\\endpoints_deactivate' ); |
This file contains 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
(function($) { | |
$.ajax({ | |
url: 'http://www.examle.com/usergroup_x/product_y/json?callback=?', | |
dataType: 'jsonp', | |
success: function (data) { | |
$('#product').html(data); | |
} | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment