0

I have this piece of code, but what I really want to do is to get all post displayed from my taxonomy. Where do I place my taxonomy slug to make sure only a certain category posts are displayed? The category slug it's let's say "projects". How to filter this category? Currently it seems that it displays all my posts on the page. Here is the code:

  $myterms = get_terms('units', 'orderby=none&hide_empty');    
  echo  $myterms[0]->name;


  foreach ($myterms as $term) :

    $args = array(
        'tax_query' => array(
            array(
                $term->slug,
            )
        )
    );
    
    //  assigning variables to the loop
    global $wp_query;
    $wp_query = new WP_Query($args);
    
    // starting loop
    while ($wp_query->have_posts()) : $wp_query->the_post();
    
    the_title();

    
    endwhile;
    
    endforeach;

1 Answer 1

2

I would recommend becoming intimately familiar with the WP_Query parameters: https://developer.wordpress.org/reference/classes/wp_query/

In your particular case; dealing with taxonomies: https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

Here is the proper code to pull from a taxonomy:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'units',
            'field'    => 'slug',
            'terms'    => $term->slug
        ),
    ),
);
$query = new WP_Query( $args );

The taxonomy should be the slug of your registered taxonomy. In this case, I'm assuming units.

2
  • Thank you @josh401, I got to this point, as a second approach, I used this: jsfiddle.net/tucado/4xuvw0c2 But it displays just one post, not all of them, so I thought this approach may not be the right one. Do you have any idea why does it display just one post Commented Dec 15, 2022 at 7:21
  • You're most welcome. You're sure you have more than one post attached to that term slug? I saw you added posts_per_page => -1, which would have been my next suggestion. I'd triple check in admin panel, go to the term management, and ensure you have more than 1 item for that slug. Otherwise, I'll keep looking.
    – josh401
    Commented Dec 15, 2022 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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