0
votes

I want to exclude a certain category by default in the list of posts shown on the front page. I found out how I can do this neatly with the pre_get_posts hook. It works fine, and the category posts don' show.
Now I want to show these category posts ONLY if I query specifically for this category. So either all posts not in this category are shown (default), or only the posts of this cat and nothing else. I thought the solution is easy, but my code doesn't work:

//Don't show posts with cat id 6
$excluded = array('6');

//Retrieve category parameter from current query
$categ = get_query_var('cat');

//If the current query doesn't ask for cat 6 specifically,
//exclude this category
if ($categ != '6') {
    set_query_var('category__not_in', $excluded);
}

But when I query for the specific category, still nothing is shown, so apparently my if statement is wrong? I thought when I query for the category, the get_query_var('cat') will return the cat id?

1
in the doc of pre_get_posts hook its stated "This hook is called after the query variable object is created, but before the actual query is run. " may be this is already excluding the cat 6 from the query - Shah Rukh
I saw this, and I understand it as "in my code, the query variables are already set", so when the query is for cat 6, get_query_var should return '6'? - dschuld
That fixed it! Thanks a million, would have never thought of that. - dschuld

1 Answers

0
votes

Found the answer through https://wordpress.stackexchange.com/questions/26889/get-query-var-and-permalinks

Apparently when using pretty permalinks, Wordpress does some internal stuff such that the category ID is not set in the query, but rather the category name. So I just changed to category resolution to

$categ = get_cat_ID(get_query_var('category_name'));

and it works fine. Yet another idea of Wordpress to annoy developers lol