0

I have 2 pages in the Wordpress site. All 2 pages are showing posts. I need to restrict few categories in First Page and other few categories from Second Page.

 <?php
    function excludeCat($query) {
      if ( $query->is_home ) {
        $query->set('cat', '-3,-5,-23');
      }
      return $query;
    }
    add_filter('pre_get_posts', 'excludeCat');
    ?>

This one will not work because, It will block the category from all the 2 pages.

1 Answer 1

0

You're nearly there, all that is left is to check on which page you currently are.

In the following code I'm first creating an array where the key corresponds to the page number and the value are the categories to exclude. This results in only one time writing $query->set(.... And to be really sure that a value exists for the key, I added isset().

<?php
function excludeCat($query) {
    $page = get_query_var('paged', 1);

    $exclude = [
        1 => '-3,-5,-23',
        2 => '...',
    ];

    if ($query->is_home && isset($exclude[$page])) {
         $query->set('cat', $exclude[$page]);
    }
    return $query;
}
add_filter('pre_get_posts', 'excludeCat');
3
  • In this line : $page = get_query_var('paged', 1);, Is the 1 is Page ID?
    – Sajeev
    Aug 24, 2018 at 6:48
  • @Sajeev No, if you check the docs, you'll see, that the 1 is the default value. If no paged is set, it returns 1, otherwise it will return the current page from 2+
    – kero
    Aug 24, 2018 at 8:07
  • It didnt worked for me. the below is my code: function excludeCat($query) { $page = get_query_var('paged', 1); $exclude = [ 12 => '-152', 8 => '-152' 11 => '15' ]; if ($query->is_home && isset($exclude[$page])) { $query->set('cat', $exclude[$page]); } return $query; } add_filter('pre_get_posts', 'excludeCat');
    – Sajeev
    Aug 26, 2018 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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