Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EdwardNavarro/5b6d04aea20bf7bca319075a5182a0f7 to your computer and use it in GitHub Desktop.
Save EdwardNavarro/5b6d04aea20bf7bca319075a5182a0f7 to your computer and use it in GitHub Desktop.
Example WordPress Simple JSON Endpoint Plugin
<?php
/**
* Plugin Name: WDS GIF API
* Plugin URI: http://webdevstudios.com
* Description: Adds a Custom Post Type to store GIFs and an API JSON Endpoint to access GIFs by a tag.
* Author: WebDevStudios
* Author URI: http://webdevstudios.com
* Version: 1.0.0
* License: GPLv2
*/
/**
* Create a Custom Post Type for our GIFs and Taxonomy to Tag Them.
*
* We are keeping this basic and passing in minimal arguments for demo purposes.
*/
function wds_gif_cpt_and_tax() {
$cpt_args = array(
'label' => 'GIFs',
'show_ui' => true,
'supports' => array( 'title', 'thumbnail' ),
);
register_post_type( 'wds_gif', $cpt_args );
$tax_args = array(
'label' => 'GIF Tags',
);
register_taxonomy( 'wds_gif_tag', 'wds_gif', $tax_args );
}
add_action( 'init', 'wds_gif_cpt_and_tax' );
/**
* Rewrite an endpoint to get GIFs.
*/
function wds_gif_endpoint() {
add_rewrite_tag( '%wds_gif%', '([^&]+)' );
add_rewrite_rule( 'gifs/([^&]+)/?', 'index.php?wds_gif=$matches[1]', 'top' );
}
add_action( 'init', 'wds_gif_endpoint' );
/**
* Pass through the data to the endpoint.
*/
function wds_gif_endpoint_data() {
global $wp_query;
$gif_tag = $wp_query->get( 'wds_gif' );
if ( ! $gif_tag ) {
return;
}
$gif_data = array();
$args = array(
'post_type' => 'wds_gif',
'posts_per_page' => 100,
'wds_gif_tag' => esc_attr( $gif_tag ),
);
$gif_query = new WP_Query( $args );
if ( $gif_query->have_posts() ) : while ( $gif_query->have_posts() ) : $gif_query->the_post();
$img_id = get_post_thumbnail_id();
$img = wp_get_attachment_image_src( $img_id, 'full' );
$gif_data[] = array(
'link' => esc_url( $img[0] ),
'title' => get_the_title(),
);
endwhile; wp_reset_postdata(); endif;
wp_send_json( $gif_data );
}
add_action( 'template_redirect', 'wds_gif_endpoint_data' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment