Skip to content

Instantly share code, notes, and snippets.

@nickkoskowski
Last active August 29, 2015 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nickkoskowski/2fb00a84b2be7f91cb30 to your computer and use it in GitHub Desktop.
Save nickkoskowski/2fb00a84b2be7f91cb30 to your computer and use it in GitHub Desktop.
Get a random post link from WP database using query
<?php
function get_random_post_link() {
$args = array(
'orderby' => 'rand',
'posts_per_page' => '1',
);
$wp_query = new WP_Query( $args );
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
$postlink = get_the_permalink();
endwhile; endif; wp_reset_query();
return $postlink;
}
?>
@widoz
Copy link

widoz commented Aug 22, 2015

May I suggest to initialize the $postlink that in case no posts where found you'll get Notice: Undefined variable: postlink in

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