Excluding Specific Terms from WP_Query

14,038

Solution 1

Final solution was to add exclude and term id to the taxonomy arguments. Since it is for taxonomy and it uses foreach loop.

$args = array(
    'parent' => 0,
    'hide_empty' => true,
    'exclude' => 13,
);

And answer for how to output custom post type posts with no taxonomy can be found here: http://www.codeforest.net/wordpress-tip-show-posts-no-category-term

Thanks to CBroe and ste for their time.

Solution 2

Your Tax Query is should be looking within another array.

'tax_query' => array(
   array(
    'taxonomy' => 'categories',
    'field'    => 'slug',
    'terms'    => array( 'special-offers', 'other-terms' ),
    'operator' => 'NOT IN',
   )
),

Rest of it seems okay. Check out the WP_Codex on this

Share:
14,038
Jack
Author by

Jack

Updated on June 06, 2022

Comments

  • Jack
    Jack almost 2 years

    I would like to create a foreach loop for taxonomy terms which is for custom post type.

    More specifically I want a loop that queries all the products categories, but not the category "special-offers" and not categories subcategories. Bonus would be if, product has no category query them too and order all of them in ASC order (Not like sort products and categories separately. All of them must be sorted at the same time).

    So what should I do with my code to make it work as needed?

    Current code:

    <?php
    
    $args = array(
        'post_type'    => 'products',
        'showposts'    => -1,
        'post_status'  => 'publish',
        'parent' => 0,
        'hide_empty' => true,
        'tax_query' => array(
            'taxonomy' => 'categories',
            'field'    => 'slug',
            'terms'    => array( 'special-offers', 'other-terms' ),
            'operator' => 'NOT IN',
        ),
    );
    
    $terms = get_terms('categories', $args );
    
    foreach ( $terms as $term ) :
    
        echo '<h2>' . $term->name . '</h2>';
    
    endforeach; 
    
    ?>
    
  • Jack
    Jack about 7 years
    Still the same result. Doesnt exclude terms.
  • ste
    ste about 7 years
    Hmm. Well at least we're on the right track now. Sorry, not currently free to help you debug this issue
  • ste
    ste about 7 years
    Glad you got it sorted. is excluding by that id the only one you want? I'd suggest looking at your original idea again. Hardcoding the ID will break if the ID is ever changed or you need to exclude another you'll have to keep adding to exclude. Try seek something more dynamic.