Question

I'm sure this is going to be a silly question... but here it goes.

I currently have a page that only displays posts of a Custom Post Type (car). I do this by running a query

$args = array(
    'post_type' => 'car');
$query = new WP_Query( $args );

On to the loop...

For this Custom Post Type i have a Custom Taxonomy e.g. Subaru, Honda etc... I'm just trying to work something else out, but if I wanted to show only posts that are Subaru's, how would I query that?

I guess I want to query the 'slug' (subaru), this code doesn't work, but you can see the route I was heading...

$args = array(
    'name' => 'subaru',
    'post_type' => 'car');
$query = new WP_Query( $args );

On to the loop...

I know name isn't right. What is the correct term to add to my $args array?

Many thanks

Was it helpful?

Solution

Depends on what your taxonomy is called. In my example its called 'brands':

$args = array(
    'post_type' => 'car',
    'brand' => 'subaru'
    );
$query = new WP_Query( $args );

see http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

OTHER TIPS

What you're trying to do is a taxonomy query. I could tell you how to do that but I think it's important I point out a much bigger mistake first. You shouldn't querying this on a page.

That's what archives are for.

Create a template file called archive-car.php and output there instead. That removes the need to run a custom WP Query.

Then create another file taxonomy-{your-custom-taxonomy-name}.php

Output the cars there as well and your problem is solved without adding any inefficient queries.

I think you need to use get_terms()

 $terms = get_terms("Subaru");
 if ( !empty( $terms ) && !is_wp_error( $terms ) ){
     echo "<ul>";
     foreach ( $terms as $term ) {
       echo "<li>" . $term->name . "</li>";

     }
     echo "</ul>";
 }

See this http://codex.wordpress.org/Function_Reference/get_terms

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top