Home > OS >  Fetching a random article in WordPress
Fetching a random article in WordPress

Time:11-07

How do I display a random post from within my wordpress site? Full title and content on a private page Different content is shown on each page refresh

CodePudding user response:

You can use wp_query orderby random. Try out this code. Use the shortcode [random_post].

<?php
add_shortcode('random_post', 'random_post_content_cb');

function random_post_content_cb(){

ob_start();
$arg = array(

    'post_type' => 'post',
     'posts_per_page' => 1,
   'orderby'=> 'rand',

);

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
  the_content();
    }
    echo '</ul>';

} else {
    // no posts found
}

$contents = ob_get_contents();
ob_end_clean();

return $contents;
}

Reference :- https://developer.wordpress.org/reference/classes/wp_query/

CodePudding user response:

You can achieve this by using php function Rand

  • Related