arie_cristianD

exclude spesific kategori on all post query

Jan 29th, 2026
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.00 KB | None | 0 0
  1. add_action(
  2.     'pre_get_posts',
  3.     function ( $q ) {
  4.         if ( is_admin() ) {
  5.             return;
  6.         }
  7.         $post_type = $q->get( 'post_type' );
  8.         if ( empty( $post_type ) ) {
  9.             $post_type = 'post';
  10.         }
  11.         if ( is_array( $post_type ) || 'post' !== $post_type ) {
  12.             return;
  13.         }
  14.  
  15.         $excluded_cat_id = 1; /* Change this with your exclulded category ID  */
  16.  
  17.         $cat_in = $q->get( 'category__in' );
  18.         if ( ! empty( $cat_in ) ) {
  19.             if ( ! is_array( $cat_in ) ) {
  20.                 $cat_in = array( $cat_in );
  21.             }
  22.             $cat_in = array_map( 'intval', $cat_in );
  23.  
  24.             if ( in_array( intval( $excluded_cat_id ), $cat_in, true ) ) {
  25.                 return;
  26.             }
  27.         }
  28.  
  29.         $existing = $q->get( 'category__not_in' );
  30.  
  31.         if ( empty( $existing ) ) {
  32.             $existing = array();
  33.         } elseif ( ! is_array( $existing ) ) {
  34.             $existing = array( $existing );
  35.         }
  36.         $existing = array_map( 'intval', $existing );
  37.  
  38.         $existing[] = $excluded_cat_id;
  39.         $merged     = array_values( array_unique( $existing ) );
  40.  
  41.         $q->set( 'category__not_in', $merged );
  42.     }
  43. );
Advertisement
Add Comment
Please, Sign In to add comment