Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Jan 12th, 2012  |  syntax: PHP  |  size: 1.43 KB  |  views: 99  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2.  
  3. global $wp_query;
  4.  
  5. // If the category name is set for this page...
  6. // (which it will be when viewing a category on the category.php template)
  7. $category_name = $wp_query->get( 'category_name' );
  8. if ( isset( $category_name ) && ! empty( $category_name ) ) {
  9.         // Now we have the category name, but we want more so we're going
  10.         // to get the full category details using the slug name.
  11.         $category_all = get_category_by_slug( $category_name );
  12.        
  13.         // Now that we have all of the category details, we can safely
  14.         // extract the category ID.
  15.         $category_id = $category_all->cat_ID;
  16.        
  17.         // Using the category ID we just obtained, we can get all the children
  18.         // of this category (returned in an array).
  19.         $category_children = get_term_children( $category_id, 'category' );
  20.        
  21.         // And now we just need to pass this array of children to exclude
  22.         // into $wp_query. We'll use query_posts() for this. Don't forget
  23.         // to merge in all of the previous arguments.
  24.         query_posts( array_merge( $wp_query->query, array(
  25.                 'category__not_in' => $category_children
  26.         ) ) );
  27. }
  28.  
  29. // Now run your WordPress loop as normal and notice that posts from
  30. // child categories no longer appear when viewing a parent category.
  31. if ( have_posts() ) : while ( have_posts() ) : the_post();
  32.  
  33.         the_title();
  34.         the_content();
  35.         // Other stuff you do
  36.  
  37. endwhile;
  38. endif;
  39.  
  40. // Lastly, you may want to rewind your posts since we used query_posts().
  41. rewind_posts();
  42.  
  43. ?>
clone this paste RAW Paste Data