0

I have created a page called "videos", this is set as the post page where all post should show up. That´s fine, but I want to exclude all posts from two of the sites categories.

I tried this code, but it´s not working it´s the right page id and the right category id´s.

    function exclude_category($query) {
    if(is_page(41)){
    $query->set('cat', '-42, -43');
    }
    return $query;
    }
    add_filter('pre_get_posts', 'exclude_category');
1

Yes your code will fail, but not because the above answer, but because this isn't the page you ask for.

As you wrote, you set the page "videos" to be the page where all the posts are shown.

When a page is set as a blogpage, Wordpress will use home.php or index.php according to the template hierarchy to display the blogpage, not a page template. This page is regarded as the home page, so is_home() will return true on this page

So, to exclude the categories, you need to use this conditional:

function exclude_category($query) {
    if(is_home()){
       $query->set('cat', '-42, -43');
    }
    return $query;
}
    add_filter('pre_get_posts', 'exclude_category');

Happy Coding,

Kuchenundkakao

  • +1 You are right, I've misread the question. For some reason I did not realise that page is set as a blogpage, which in any case Wordpress will use home.php or index.php, not a page template to display the blogpage. Also is_home will return true on this page. I'm going to leave my answer for extra info. – Pieter Goosen Jul 23 '14 at 10:17
  • I've made the necessary changes to the answer (and upvoted it) to include my comment. If any one has a problem with this, please roll back my changes – Pieter Goosen Jul 23 '14 at 10:24
0

EDIT:

I have misread the question and did not realise that the page is set as blogpage. I'm keeping this answer as extra information just to serve someone about pre_get_posts and page templates. I have added additional info to the upvoted answer about blogpage and is_home*

ORIGINAL ANSWER:

Your code will fail, as you have already discovered. pre_get_posts does not work on page templates

pre_get_posts cannot be used to alter the query for Page requests (page templates) because is_page, is_singular, pagename and other properties (depending if pretty permalinks are used) are already set by the parse_query() method. See: Query Overview. The recommended way to alter the main query for page requests is to use new WP_Query in the page template itself.

You solution would be to go and create a custom query on the page you need it with WP_Query. Go and check out the category parameters and example on the codex page

UPDATE 20-01-2015

For running pre_get_posts on true pages, see Using pre_get_posts on true pages and static front pages

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.