Skip to content

Instantly share code, notes, and snippets.

@airesvsg
Created November 2, 2016 00:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airesvsg/2710de81f09613c456277ae3e38c2358 to your computer and use it in GitHub Desktop.
Save airesvsg/2710de81f09613c456277ae3e38c2358 to your computer and use it in GitHub Desktop.
random gallery image
<?php
// element where displays the image
// copy the snippet below and paste where you want to show the image.
// <div class="random-gallery-image" data-id="<?php echo the_ID(); ?>"></div>
// Copy these functions below and paste in your functions.php
add_action( 'rest_api_init', function() {
register_rest_route( 'gallery', '/random/(?P<id>\d+)', array(
'methods' => WP_REST_Server::READABLE,
'callback' => function( $request ) {
$id = (int) $request->get_param( 'id' );
if ( $id && $gallery = get_field( 'gallery', $id ) ) {
shuffle( $gallery );
return $gallery[0];
}
return new WP_Error( 500, 'invalid gallery' );
}
) );
} );
add_action( 'wp_footer', function() { ?>
<script>
( function( $ ) {
var url = '<?php echo site_url( '/wp-json/gallery/random/' ); ?>';
$( '.random-gallery-image' ).each( function() {
var self = $( this );
var id = self.data( 'id' );
$.get( url + id, function( data ) {
if ( data ) {
$( new Image() ).load( function() {
var img = $(this);
img.hide();
self.append( img );
img.width( data.width )
.height( data.height )
.fadeIn( 'fast' );
} )
.attr( {
src: data.url
} );
}
} );
} );
} ) ( jQuery );
</script>
<?php } );
@dbrabyn
Copy link

dbrabyn commented Jan 2, 2017

This returns the image at full size. How would I return it at my custom image size?

Thanks so much for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment