0

I'm not much of a PHP dev (front-end dev, mainly) and I'm struggling with getting a custom taxonomy term to display all posts using that term.

Here's the deal. I have: 1. A custom post type (attorneys) 2. A custom taxonomy for that post type (practice-areas) 3. A specific taxonomy term (appeals)

I need to display all "attorneys" posts that use the term "appeals" from the custom taxonomy "practice-areas". This will be displayed on the index page so I need to be specific with the query.

Here's my loop as it stands now:

$loop = new WP_Query( array( 'post_type' => 'attorneys', 'tax_query' => array( 'taxonomy' => 'practice-areas', 'field' => 'term_id', 'terms' => 'appeals', ) ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> // Get the content the_content; //Blah blah blah close loop ?>

  • It should be noted this loop kinda works but isn't selecting the attorney post type by taxonomy term. It's simply printing all the attorneys without the taxonomy term filter. – Rocketpig Nov 27 '16 at 19:05
0

You have a problem with the tax_query arrays

array(
        'post_type' => 'attorneys',
        'tax_query' => array(
            'taxonomy' => 'practice-areas',
            'field' => 'slug',
            'terms' => 'appeals',
            )
        )

The tax_query parameter in $loop must look like this:

     $loop = new WP_Query(
        array(
            'post_type' => 'attorneys',
            'tax_query' => array(
                array(
                    'taxonomy' => 'practice-areas',
                    'field' => 'term_id',
                    'terms' => 'appeals',
                )
            )
        )
    );

The tax_query parameter must be an array of array and the field parameter slug (as terms is not the term_id).

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.

You can read more about the parameters available and their default values Codex WP_Query

Hope it works!

  • Just a note, if you really want to display all "attorney posts, you might be tempted to set the posts_per_page parameter to -1, but don't. Pagination is always better. – Charles Jaimet Nov 27 '16 at 20:04
  • Yes, @Charles, and I just edit my answer about the field parameter to change. – Benoti Nov 27 '16 at 20:07
  • Ah, yes, thank you! I read somewhere tax terms need to be an array within an array but forgot to implement that in my loop. – Rocketpig Nov 27 '16 at 22:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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