Skip to content

Instantly share code, notes, and snippets.

@shizhua
Last active September 30, 2016 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shizhua/1755f481cb076a5cc973 to your computer and use it in GitHub Desktop.
Save shizhua/1755f481cb076a5cc973 to your computer and use it in GitHub Desktop.
Create a Random Post button in WordPress
<div class="random-post-button">
<a href="random post url">Random Post</a>
</div>
<?php
$args = new WP_Query(array(
'posts_per_page' => '1',
'no_found_rows' => true,
'orderby' => 'rand',
'ignore_sticky_posts' => true,
));
if ( $args->have_posts() ) :
while ( $args->have_posts() ) : $args->the_post();
$random_url = get_permalink(); ?>
<!--random button tags here-->
<?php endwhile; ?>
<?php endif; wp_reset_query(); ?>
<?php
function random_post_button() {
$args = new WP_Query(array(
'posts_per_page' => '1',
'no_found_rows' => true,
'orderby' => 'rand',
'ignore_sticky_posts' => true,
));
if ( $args->have_posts() ) :
while ( $args->have_posts() ) : $args->the_post();
$random_url = get_permalink(); ?>
<div class="random-post-button">
<a href="<?php echo $random_url;?>">Random Post</a>
</div>
<?php endwhile;
endif; wp_reset_query();
}
<?php random_post_button(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment