<img src="http://example.com/api/images/random">
<?php
/**
* Creates endpoint to select random image from Library
*
* http://example.com/api/images/random
*
*/
if ( ! class_exists( 'Endpoint_RandomImage' ) ):
/**
* The code that registers the endpoint and handles the result
*/
class Endpoint_RandomImage {
const ENDPOINT_NAME = 'api/images/random'; // endpoint to capture
const ENDPOINT_QUERY_NAME = '__api_images_random'; // turns to param
// WordPress hooks
public function run() {
add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );
add_action( 'parse_request', array( $this, 'sniff_requests' ), 0 );
add_action( 'init', array( $this, 'add_endpoint' ), 0 );
}
// Add public query vars
public function add_query_vars( $vars ) {
$vars[] = static::ENDPOINT_QUERY_NAME;
$vars[] = 'extra';
return $vars;
}
// Add API Endpoint
public function add_endpoint() {
add_rewrite_rule( '^' . static::ENDPOINT_NAME . '?$', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1', 'top' );
add_rewrite_rule( '^' . static::ENDPOINT_NAME . '/([^/]+)/?$', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&extra=$matches[1]', 'top' );
// --->
flush_rewrite_rules( true ); //// <---------- REMOVE THIS WHEN DONE TESTING
// --->
}
// Sniff Requests
public function sniff_requests( $wp_query ) {
global $wp;
if ( isset( $wp->query_vars[ static::ENDPOINT_QUERY_NAME ] ) ) {
$this->handle_request(); // handle it
}
}
// Handle Requests
protected function handle_request() {
global $wp;
$image_ids = get_posts(
array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'numberposts' => 1,
'orderby' => 'rand',
'fields' => 'ids',
) );
// convert ids to urls
// $images = array_map( "wp_get_attachment_url", $image_ids );
// convert ids to paths
$images = array_map( "get_attached_file", $image_ids );
$image_id = $image_ids[ 0 ];
$image_path = $images[ 0 ];
// make sure url is readable -- if not, stop!
if ( ! is_readable( $image_path ) ) {
wp_die( "File is not readable: $image_path" );
}
// get files contents
$image = file_get_contents( $image_path );
// get the mime type for headers
$type = get_post_mime_type( $image_id );
if ( empty ( $type ) ) {
$type = "image/jpg";
}
// output headers and image data
nocache_headers();
header( "Content-type: $type;" );
header( "Content-Length: " . strlen( $image ) );
echo $image;
die(); // fin
}
}
$ep = new Endpoint_RandomImage();
$ep->run();
endif; // Endpoint_RandomImage
Use a custom endpoint to grab a random image from the Media Library and display it to the screen.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.