If the given code is correct it might be the missing brackets on your pre_get_posts
conditional. Let’s format it with proper indentation and spacing:
function alter_query( $query ) {
if( $query->is_main_query() && is_home() )
$query->set( 'cat', '2' );
$query->set( 'orderby', 'rand' );
}
add_action( 'pre_get_posts','alter_query' );
Because there’s no brackets for your conditional statement, it will run the first line inside the conditional and all other lines outside. It’s shorthand. To fix this we just need to add brackets:
function alter_query( $query ) {
if( $query->is_main_query() && is_home() ) {
$query->set( 'cat', '2' );
$query->set( 'orderby', 'rand' );
}
}
add_action( 'pre_get_posts','alter_query' );
By encapsulating the additional functionality in brackets we ensure that all statements are run only if that condition is met.