• Resolved stpetersphila

    (@stpetersphila)


    I am looking to exclude posts with a particular category, but not when they also have a second category that is not excluded. So if I have categories A, B, C and D, I want to include all posts except those categorized ONLY A.

    I know that I can exclude a category by placing the following in functions.php

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

    but then any post with category ID 5 is excluded regardless of what other categories the post may have.

    I could also expressly include all categories except the excluded one

    function include_categories( $query ) {
        if ( $query->is_home() && $query->is_main_query() ) {
            $query->set( 'cat', '3,4,5' );
        }
    }
    add_action( 'pre_get_posts', 'include_categories' );

    but I would rather not need to rewrite functions.php every time the blog adds a new category.

    Is there a way (or a plug-in) that can operate like the second function without needing to be recoded when new categories are added?

Viewing 3 replies - 1 through 3 (of 3 total)
  • $query = new WP_Query( array( 'category__not_in ' => array( 2, 6 ) ) );

    Tells the query to exclude posts with category ID 2 and 6.

    Thread Starter stpetersphila

    (@stpetersphila)

    Thank you for your response, Evan. However that code functions the same as my first function: excluding all posts with that category regardless of other categories the post may have.

    I am looking, rather than to exclude a category, to fail to include a particular category.

    Thread Starter stpetersphila

    (@stpetersphila)

    I’ve figured out code works. I’ve put this in my functions.php file, and it behaves as expected, not including posts categorized ONLY as excluded categories, but including posts categorized with an excluded and NONexcluded category.

    I’ll mark as resolved in a day or two if nobody chimes in with a more elegant solution.

    function exclude_categories( $query ) {
     if ( $query->is_home() && $query->is_main_query() ) {
      $cats = array();
      $category_ids = get_all_category_ids();
      foreach( $category_ids as $cat_id ) {
       if ( ( $cat_id != 1) && ( $cat_id != 5) && ( $cat_id != 40) ){
        $cats[] = $cat_id;
       }
      }
      $query->set( 'category__in', $cats );
     }
    }
    add_action( 'pre_get_posts', 'exclude_categories' );

    I struggled for a while before I realized I couldn’t pass an array to ‘cat’.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Exclude post with category A, but not with A and B’ is closed to new replies.