-1

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">';

Progman
  • 16,827
  • 6
  • 33
  • 48

2 Answers2

2

You should define the variable $string before using it. Try putting this line

$string = '';

at the beginning of the function.

pazkou
  • 71
  • 4
0

You are trying to append (.=) to a string that wasn't declared. Try replacing .= with = on line 29

Hillel
  • 811
  • 2
  • 7
  • 19