0

So I have a custom Wordpress wp_query loop within taxonomy.php that is showing all custom post type posts, sorted by a custom meta field (start_date). Within this template I have links to each taxonomy child that uses the same page template. This does not work using the loop code I have, shown below.

I want this loop to be able to detect the current taxonomy and show posts in that taxonomy only. So for example my setup is as follows:

  • Themes (Taxonomy name)
  • Poetry
  • Politics
  • Environment
  • etc.

So when you visit http://example.com/themes I want to show all posts within this taxonomy but when you visit http://example.com/themes/poetry for example, I want to show only show Poetry posts.

Here's my loop:

$today = date('Ymd');

$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

$args = array (
  'post_type' => 'whatson',
  'meta_query' => array(
    array(
        'key' => 'start_date',
        'compare' => '>=',
        'value' => $today,
    )
  ),
  'tax_query' => array(
        array(
            'taxonomy' => $term->name,
            'field'    => $term->slug
        ),
    ),
  'meta_key' => 'start_date',
  'orderby' => 'meta_value',
  'order' => 'ASC',
);
$query = new WP_Query( $args );


if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

This code breaks the template and when I print the query to see what is returned I get the following result:

Array ( 

[post_type] => whatson 

[meta_query] => Array ( [0] => Array ( [key] => start_date [compare] => >= [value] => 20170213 ) ) 

[tax_query] => Array ( [0] => Array ( [taxonomy] => Politics [field] => politics ) ) 

[meta_key] => start_date 

[orderby] => meta_value 

[order] => ASC 
)
0

From the above query, it seems that you have passed wrong parameters in tax_query of your query.

It should be as follows:

'tax_query' => array(
       array(
           'taxonomy' => 'Themes', //Your custom taxonomy slug
           'field'    => 'slug', // this should be field name, not field value
           'terms'                => array('environment'),
           'include_children' => true,      
               'operator' => 'IN'  
       ),
   ),

Hope this will help you.

1
  • That's it, I think its working correctly. Thanks! I'm a first timer when it comes to taxonomies so I'm learning all the time at the mo. – egr103 Feb 13 '17 at 14:42

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.