Random Post REST Endpoint
Adds a public /wp-json/site/v1/random endpoint that returns one random published post with its title, link and excerpt, for "surprise me" buttons or widgets.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
register_rest_route( 'site/v1', '/random', array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => '__return_true',
'callback' => function () {
$ids = get_transient( 'wpide_random_post_ids' );
if ( false === $ids ) {
$ids = get_posts( array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 500,
'fields' => 'ids',
'no_found_rows' => true,
'has_password' => false,
) );
set_transient( 'wpide_random_post_ids', $ids, HOUR_IN_SECONDS );
}
if ( ! $ids ) {
return new WP_Error( 'no_posts', 'No posts found.', array( 'status' => 404 ) );
}
$post = get_post( $ids[ array_rand( $ids ) ] );
return rest_ensure_response( array(
'id' => $post->ID,
'title' => get_the_title( $post ),
'link' => get_permalink( $post ),
'excerpt' => wp_strip_all_tags( get_the_excerpt( $post ) ),
) );
},
) );
} );
add_action( 'save_post_post', function () {
delete_transient( 'wpide_random_post_ids' );
} );
Notes
The list of candidate IDs is cached for an hour and refreshed when you publish or update a post.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.