0

I'm trying to retrieve a random post to link to on my site. I have the following code, but the only thing that it seems to retrieve and display is a link to the homepage. Any help would be appreciated!

$args = array(
'posts_per_page'   => 1,
'orderby'          => 'rand',
'post_status'      => 'publish',
);

$the_query = new WP_Query($args);

while ( have_posts() ) : the_post();
    echo '<a href="';
    echo the_permalink();
    echo '" title="';
    echo the_title();
    echo '">';
    echo the_title();
    echo '</a>';
endwhile;

wp_reset_query();
2

You need to specify the post type to be a post - try this for your $args instead:

$args = array(
    'post_type'        => 'post', // Specifying you want posts only
    'posts_per_page'   => 1,
    'orderby'          => 'rand',
    'post_status'      => 'publish',
);

And most importantly, you need to apply the $args to your query, so do this for the loop:

while ( $the_query->have_posts() ) : $the_query->the_post();

See this in the Codex.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.