Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Created August 25, 2014 02:08
Show Gist options
  • Save Shelob9/2b7fd77cf04ea4db475b to your computer and use it in GitHub Desktop.
Save Shelob9/2b7fd77cf04ea4db475b to your computer and use it in GitHub Desktop.
Example code, packaged as a plugin for my Torque article on getting posts via GET requests using the WordPress REST API. http://torquemag.io/?p=72403
<?php
/*
Plugin Name: JP Mini REST API GET Client
Plugin URI: http://torquemag.io/?p=72403
Description: A min client for making GET requests via the WordPress REST API.
Version: 0.1.1
Author: Josh Pollock
Author URI: http://JoshPress.net
License: GPL v2 or later
*/
/**
* Makes a GET request to the WP REST API & returns JSON Object
*
* @param string $url URL to GET
*
* @return array|WP_Error Array of post objects on success or WP_Error object on failure.
*/
function jp_mini_rest_get_json( $url ) {
//GET the remote site
$response = wp_remote_get( $url );
//Check for error
if ( is_wp_error( $response ) ) {
return sprintf( 'The URL %1s could not be retrieved.', $url );
}
//get just the body
$data = wp_remote_retrieve_body( $response );
//return if not an error
if ( ! is_wp_error( $data ) ) {
//decode and return
return json_decode( $data );
}
}
/**
* Builds a URL string for making GET requests for the WP REST API
*
* @see http://wp-api.org/#posts_retrieve-posts
*
* @param string|array $post_types Post type(s) to query for. Can be on post type as a string or an array of post types. Default is 'post'
* @param bool|array $filters Optional. Filters to use in query. Should be an array in form of filter => value. See REST API docs for possible values. The default is false, which skips adding filters.
* @param string $base Optional. Base for making request. Default is 'wp-json/posts?
*
* @return string|void
*/
function jp_mini_rest_posts_url_string( $post_types = 'post', $filters = false, $rooturl = 'home_url', $base = '/wp-json/posts?' ) {
if ( is_callable( $rooturl ) ) {
$url = call_user_func( $rooturl );
$url = $url.$base;
}
else {
$url = $rooturl.$base;
}
if ( is_string( $post_types ) ) {
$post_types = array( $post_types);
}
foreach ( $post_types as $type ) {
$url = add_query_arg( "type[]", $type, $url );
}
if ( $filters ) {
foreach( $filters as $filter => $value ) {
$args[ "filter[{$filter}]" ] = $value;
}
$url = add_query_arg( $args, $url );
}
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment