0

I would like to hide a post on the main blog page (run on index.php) and have it only show up when the visitor views a particular category.

I have tried the following just before the loop:

<?php query_posts('cat=-208'); ?>

This hides the post in blog view as intended, but when I click into category 208 all posts show up there, even those not tagged with that category. However, the post tagged with that category does not show up there either.

Please help.

  • 1
    Never use query_posts. Search Codex for pre_get_posts. – Milo Feb 11 '15 at 14:42
  • 1
    Thanks, that led me to an answer. If you add that as an answer, I'll accept it. – Marc Feb 11 '15 at 14:49
  • Marc, better if you post your full solution please as link only answers will likely be removed. – David Gard Feb 11 '15 at 16:22
  • Remove a post or entire category of posts? – Brad Dalton Feb 12 '15 at 13:09
1

I was able to get the result that I wanted by putting the following into the functions.php file in my theme directory:

function exclude_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', '-208' );
    }
}
add_action( 'pre_get_posts', 'exclude_category' );

The result of using this code was that any posts tagged with category 208 do not appear in the main blog, but they do appear in category 208 as well as in any other categories they are tagged with.

To exclude multiple categories, edit the following line of the above as follows:

$query->set( 'cat', '-208,-9,-50' );

You can find full details here.

Thanks to Milo for his comment pointing me in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.