I want to exclude a category and order the results by date with query_posts while preserving existing query parameters and order the results by date.
According to the Wordpress documentation I should add (or over-ride) parameters in the following way:
global $query_string;
query_posts( $query_string . '&orderby=date&order=ASC&cat=-1' );
The results are right but ordering them by date doesn't work (ASC and DESC).
Only ordering the results works fine:
global $query_string;
query_posts( $query_string . '&orderby=date&order=ASC' );
Only excluding a category, without ordering the results, works fine:
global $query_string;
query_posts( $query_string . '&cat=-1 );
Also including certain categories and ordering the results works fine:
global $query_string;
query_posts( $query_string . '&orderby=date&order=ASC&cat=2' );
Of course I can work around it by building an array of the right categories first, then use these categories in the query_posts. Something like the following:
$include = array();
$categories = get_categories( array('exclude' => 1) );
foreach ( $categories as $category ) {
$include[] = $category->term_id;
}
But I can't figure out why the combination of excluding a category and ordering by date doesn't work when using query_posts.
Tested with versions 3.9.1 and 4.0.1 of Wordpress. Both giving same results.
Is this a bug in Wordpress or is it something in my code?
EDIT:
Tested WP_Query and pre_get_posts based on comments but both returning same results as query_posts.
WP_Query example
$args = array(
'category__not_in' => array(1),
'post_type' => 'post',
'orderby' => 'date',
'order' => 'ASC',
);
// The Query
$query = new WP_Query( $args );
pre_get_posts example
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'orderby', 'date' );
$query->set( 'order', 'ASC' );
$query->set( 'cat', '-1' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );
Everything works fine until a category is excluded.