Wednesday, March 2, 2022

[FIXED] Excluding Specific Terms from WP_Query

Issue

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; 

?>

Solution

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.



Answered By - Jack

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.