I have this code that generates a link to a random post in my blog:
<?php
$posts = get_posts('orderby=rand&numberposts=1');
foreach($posts as $post): ?>
<a href="<?php the_permalink(); ?>" title="Random Post from Our Blog" style="float:right;" class="random-widget">
<span class="fa-random" style="font-family:FontAwesome;float:right;"></span>
</a>
<?php endforeach;
wp_reset_postdata(); ?>
I replaced wp_reset_query()
with wp_reset_postdata()
after reading this question but it's not working for me. All of my pages are displaying random post content instead of the page content. This is called in my action bar, above the menu.
Update
After several iterations, my code now closely resembles that found in the Codex and I'm still experiencing the same problem. Here's what I've got so far:
<?php
global $post;
$args = array('orderby'=>'rand','numberposts'=>'1','offset'=>'0');
$posts = get_posts($args);
foreach($posts as $post): setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>" title="Random Post from Our Blog" style="float:right;" class="random-widget">
<span class="fa-random" style="font-family:FontAwesome;float:right;"></span>
</a>
<?php endforeach;
wp_reset_postdata(); ?>
numberposts
withposts_per_page
?get_posts
doesn't modify global variables and should be safe to use anywhere. The question that you linked is usingquery_posts
which does and should be avoided at any cost.