Skip to content

Instantly share code, notes, and snippets.

@lloc
Last active August 3, 2018 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lloc/8935425 to your computer and use it in GitHub Desktop.
Save lloc/8935425 to your computer and use it in GitHub Desktop.
<?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' );
(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