When I put this code block in functions.php file under Wordpress theme folder.
###########Display Random Posts in WordPress Using Code######################
function wpb_rand_posts() {
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 20,
'cat' => '-5400,-5404',
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$string .= '<ul class="menu wpb-random-posts">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= '<li><a href="'. get_permalink() .'">'. 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');
I will have this error:
PHP Notice: Undefined variable: string in /home/..../wp-content/themes/.../functions.php on line 29
This code block is meant to display a list of random wordpress posts on sidebar as a widget. It works, but with this error keep adding to php.error.log file, thousands of lines now..
line 29 refers to
$string .= '<ul class="menu wpb-random-posts">';