Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

1 Answer

get_category_by_slug() returns a category object or FALSE:

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

Result:

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
add comment

Your Answer

 
discard

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.