Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Liam Maclachlan
Liam Maclachlan
22,805 Points

How do you get the WordPress loop to show only posts that exaclty match an array of categories, not just one?

I am trying to display all news and events posts (different cateogries based on Publisher) on a banner across the top of the website but am trying to define there parent category, too. Any ideas?

Liam Maclachlan
Liam Maclachlan
22,805 Points

I have found this:

$query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) );

But I really need to be a slug/string, not an int

1 Answer

Liam Maclachlan
Liam Maclachlan
22,805 Points

Found it! Check the post here, Here is the function:)

<?php get_term_by( $field, $value, $taxonomy, $output, $filter ) ?>

And here is an example:

// fetching the category id's 
<?php $theCatId = get_term_by( 'slug', get_the_title(), 'category' ); ?>
<?php $newsCat =  get_term_by( 'slug', 'news', 'category' ); ?>

// the custom loop
<?php $args = array( 'post_type' => 'news', 'category__and' =>  array($newsCat->term_id, $theCatId->term_id) );?>
<?php $query = new WP_Query($args); ?>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
    // the content
<?php endif; endwhile; ?>
Zac Gordon
Zac Gordon
Treehouse Guest Teacher

Nice :) thanks for sharing the solution :)

Liam Maclachlan
Liam Maclachlan
22,805 Points

Just realised... I don't think it is using the news category in the loop, only the one converted to an int. I haven't set the ID of it. Oops. I'll change that shortly. :$