I have the following code in my home.php

<?php query_posts($query_string . '&orderby=rand' . '&cat=-182,-184'); ?>

query_posts seems not the best solution. What would be the best way pre_get_post or WP Query.

Highly appreciated if you could also write the correct code.

Kind regards,



pre_get_posts in your child themes functions file is the best in my opinion.

add_action( 'pre_get_posts', 'wpsites_custom_get_posts' );

function wpsites_custom_get_posts( $query ) {

if( $query->is_main_query() && $query->is_home() ) {

$query->set( 'cat', '-182,-184' );

$query->set( 'posts_per_page', '12' );

$query->set( 'orderby', 'RAND' );

This method is more flexible in my opinion.

|improve this answer|||||
  • TIL this is the best solution for editing main loop. Source – NW Tech Feb 6 '14 at 17:28

You will want to use new WP_Query. Here's why.

Here's an example of what you might try:

    'posts_per_page' => -1,
    'orderby'   => 'rand',
    'category__not_in' => array(182, 184)

$query = new WP_Query($args);

if( $query->have_posts() ) { while ($query->have_posts()) : $query->the_post();

    // Do loop stuff here

endwhile; }

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.