Developers Diary

Pre Get Posts Code

Featured Post Image - Pre Get Posts Code

Code snippet to put in functions.php to remove some categories from the main loop.  I’m seeing how I like my blog with photography and personal categories out of my usability blog.

wordpress pre get posts

//https://wordpress.stackexchange.com/questions/44672/exclude-the-category-from-the-wordpress-loop ------ removes categories personal and photography from the main loop
add_action('pre_get_posts', 'wpa_44672' );

function wpa_44672( $wp_query ) {

//$wp_query is passed by reference. we don't need to return anything. whatever changes made inside this function will automatically effect the global variable

$excluded = array(207,97); //made it an array in case you need to exclude more than one

// only exclude on the home page
 if( is_home() ) {
 set_query_var('category__not_in', $excluded);
 //which is merely the more elegant way to write:
 //$wp_query->set('category__not_in', $excluded);
 }
}