1

I'm trying to hide posts from a specific category from being featured. Currently, the section shows featured posts from all categories. I need to exclude posts from a category (with category name not by id).

$args = array(
    'posts_per_page' => 1,
    'meta_key'       => 'meta-checkbox',
    'meta_value'     => 'yes',
    );
$featured = new WP_Query( $args );
  • 1
    so what is the question? – Mark Kaplun Sep 20 '16 at 14:15
  • @MarkKaplun "I need to exclude posts from a specific category" – Kishor Parmar Sep 20 '16 at 14:19
  • 1
    that is a statement, not a question :( – Mark Kaplun Sep 20 '16 at 14:27
4

Excluding specific categories from WP_Query

This is in the codex. You can exlclude specific categories from WP_Query. Where array(2, 6) are IDs for categories to be excluded in this example.

$query = new WP_Query( array( 'category__not_in' => array( 2, 6 ) ) );

See the codex: https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

NOTE: If you are trying to exclude category by the name of category

First you would do this to find the category ID by providing category name.

$category_id = get_cat_ID( 'My Category' );

then add the returned $category_id in your WP Query arguments it would look like this:

$query = new WP_Query( array( 'category__not_in' => array( $category_id ) ) );
-1

you can add 'exclude' => '', in your args array

or just provide the category id ,comma separated like below

$args = array(
    'posts_per_page' => 1,
    'meta_key' => 'meta-checkbox',
    'meta_value' => 'yes',
'category'         => '2,3,4,5,6,7,8',
    );

See this link :https://codex.wordpress.org/Template_Tags/get_posts

  • I was using 'cat' instead of 'category'. Thanks @vanurag – Kishor Parmar Sep 20 '16 at 14:25
  • Glad that it worked !!! – vanurag Sep 20 '16 at 14:27
  • 2
    this code is including, not excluding :( – Mark Kaplun Sep 20 '16 at 14:30
  • Sorry. not worked :( @vanurag . I refreshed live version website instead of localhost. – Kishor Parmar Sep 20 '16 at 14:31
  • To exclude any category you just need to put minus (-) with category ID. For example in your code line 'category' => '2,3,4,5,6,7,8',. Suppose you need to exclude 2 and 3 ID then put minus with them like this 'category' => '-2,-3,4,5,6,7,8',. Then 2 and 3 ID will get removed. And I use cat for category instead of category. But if its working fine for you then ok. You can update your answer with that solution :) – Rishabh Sep 21 '16 at 4:25

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.