WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I set the values for category__not_in from two variables. On my example I just hardcode the ID of each category to exclude, but... how can I pass these values from some variables ?

    $category_a = get_category_by_slug('fbrt');
    $category_b = get_category_by_slug('contact');

    $exclude = get_the_ID();
    global $wp_query;
    $exclude = $wp_query->post->ID;
    $args = array(
        'category_name' => 'olympic-physique',
        'category__not_in' => array(1, 2),
        'posts_per_page' => -1,
        'orderby' => 'title', 
        'order' => 'DESC'
share|improve this question

get_category_by_slug() returns a category object or FALSE:

$cat1 = get_category_by_slug( 'cata' );
print '<pre>' . htmlspecialchars( print_r( $cat1, TRUE ) ) . '</pre>';


stdClass Object
    [term_id] => 3
    [name] => Cat A
    [slug] => cata
    [term_group] => 0
    [term_taxonomy_id] => 3
    [taxonomy] => category
    [description] => 
    [parent] => 0
    [count] => 2
    [cat_ID] => 3
    [category_count] => 2
    [category_description] => 
    [cat_name] => Cat A
    [category_nicename] => cata
    [category_parent] => 0

So, to get an array of IDs just check if you get an object for each slug and add the term_id to the array:

$category__not_in = array();
$slugs            = array ( 'cata', 'catdoesnotexist' );
foreach ( $slugs as $slug )
    $cat = get_category_by_slug( $slug );
    $cat and $category__not_in[] = $cat->term_id;
$args = array (
    'category__not_in' => $category__not_in

Instead of hard coding the slugs in your script consider to add term meta data to the categories. You will need an additional query to find all needed terms, but your script stays reusable.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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