Henrique Giuliani
Henrique Giuliani

Reputation: 296

WP_Query for getting posts under custom taxonomy not working

I am trying to get custom post types from a custom taxonomy. Following the documentation and other similar problems related here, i did the following:

$query = new WP_Query( array(
  'post_type' => 'job',
  'tax_query' => array(

     'taxonomy' => 'location',
     'field' => 'slug',
     'terms' => 'california'
   )
)

But the problem is that this query is getting all posts, not just posts under "California" taxonomy.

If more information is needed, i can provide more code editing the question.

Thanks in advance!

Upvotes: 0

Views: 3377

Answers (3)

Nathan Dawson
Nathan Dawson

Reputation: 19318

You're missing an array. The tax query argument can be used for multiple taxonomies. It accepts an array of arrays.

Important Note: tax_query takes an array of tax query arguments arrays (it takes an array of arrays). This construct allows you to query multiple taxonomies by using the relation parameter in the first (outer) array to describe the boolean relationship between the taxonomy arrays.

https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

Change this:

'tax_query' => array(

     'taxonomy' => 'location',
     'field' => 'slug',
     'terms' => 'california'
   )

To this:

'tax_query' => array(
    array(
        'taxonomy' => 'location',
        'field'    => 'slug',
        'terms'    => 'california',
    ),
),

Upvotes: 1

Mukesh Ram
Mukesh Ram

Reputation: 6338

Try something like this:

    $posts_array = get_posts(
        array(
            'posts_per_page' => -1,
            'post_type' => 'job',
            'tax_query' => array(
                array(
                    'taxonomy' => 'location',
                    'field' => 'slug',
                    'terms' => 'california',
          )
        )
    )
);

Upvotes: 3

PHPer
PHPer

Reputation: 674

In your while loop, remember to switch

<?php

  while ( $query->have_posts() ) {
     $query->the_post();   
      // Important line, especially if you have
      //multiple WP_Query  invocations

     DO WHAT YOU WANT HERE

  wp_reset_postdata();
  }

 ?>

Upvotes: -1

Related Questions