lmartins
8/10/2015 - 9:39 AM

Query posts using the same taxonomy as the current post

Query posts using the same taxonomy as the current post

/**
 * QUERY DESIGNS DO VERTICAL
 * http://wordpress.stackexchange.com/questions/139571/display-posts-with-same-taxonomy-term
 */

$vertical_terms = wp_get_object_terms( $post->ID,  'vertical_cat' );

if( $vertical_terms ){

    // going to hold our tax_query params
    $tax_query = array();

    // add the relation parameter (not sure if it causes trouble if only 1 term so what the heck)
    if( count( $vertical_terms > 1 ) )
        $tax_query['relation'] = 'OR';

    // loop through verticals and build a tax query
    foreach( $vertical_terms as $term ) {
        $tax_query[] = array(
            'taxonomy' => 'vertical_cat',
            'field' => 'slug',
            'terms' => $term->slug,
        );
    }

    $args = array(
    	'post_type'   => 'vertical',
    	'orderby'     => 'menu_order',
    	'order'       => 'ASC',
    	'post__not_in'     => array(  $post->ID ),  // exclui o post que já está destacado
    	'tax_query' => $tax_query
    );
    $context['designs'] = Timber::get_posts( $args );

}