Retrieve Post in Wordpress

Random Post Retrieve

Enter functions.php

function wpb_rand_posts() { 
$args = array(
    'post_type' => 'post',
    'orderby'   => 'rand',
'cat' => 6,
    'posts_per_page' => 5, 
    );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$string .= '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        $string .= '<li class="text-white"><a href="'. get_permalink() .'" class="text-white">'. get_the_title() .'</a></li>';
    }
    $string .= '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
$string .= 'no posts found';
}
return $string; 
add_shortcode('wpb-random-posts','wpb_rand_posts');
add_filter('widget_text', 'do_shortcode');

and enter shortcode where you want list:

<?php echo do_shortcode('[wpb-random-posts]'); ?>

Comments