number of posts per page + random + exclude categories

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,


Solutions Collecting From Web of "number of posts per page + random + exclude categories"

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.

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; }