After this piece of PHP code is added to my template (Wordpress) my server goes bananas. (I see lots of load peaks, it becomes unresponsive and the site won't load until I reboot the server.)
The code just displays random posts from the database:

$random_query = new WP_Query('posts_per_page=4&orderby=rand');
while($random_query->have_posts()) : $random_query->the_post(); global $post; ?>

	<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><img src="<?php echo get_post_meta($post->ID, 'thumbnail', true); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" /></a>

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>

Does anyone know how can I optimize this piece of code to avoid having all these problems?

you dont need to instanciate a new wp_query if you are in your template fine.. you just need to use query_post() function with arguments.

Here is the codex. link

// The Query
query_posts( $args );

// The Loop
while ( have_posts() ) : the_post();
    echo '<li>';
    echo '</li>';

// Reset Query
This article has been dead for over six months. Start a new discussion instead.