-
-
Save airesvsg/2710de81f09613c456277ae3e38c2358 to your computer and use it in GitHub Desktop.
random gallery image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 } ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This returns the image at full size. How would I return it at my custom image size?
Thanks so much for your help.