WordPress.org

Support

Support » Themes and Templates » Group Posts by Taxonomy on Category pages

Group Posts by Taxonomy on Category pages

  • Hello,

    I need some major help with this. I want to be able to display posts on the category template in groups, not just a straight list. for example, I want to be able to click on ‘Architecture’ (as the category), and when it opens up, all articles under this category should be further sorted into ‘Books’, ‘Articles’ and ‘Reports’.

    Does anyone know if this is possible, or has anyone implemented anything like this before? I’ve searched both this forum and google, but either I’m not using the correct terminology for the search, or noone has actually done this before (which is hard to believe!).

    I’d appreciate any help possible.

Viewing 2 replies - 1 through 2 (of 2 total)
  • I found this in the codex:

    $args = array(
    	'tax_query' => array(
    		'relation' => 'OR',
    		array(
    			'taxonomy' => 'category',
    			'field' => 'slug',
    			'terms' => array( 'quotes' ),
    		),
    		array(
    			'taxonomy' => 'post_format',
    			'field' => 'slug',
    			'terms' => array( 'post-format-quote' )
    		)
    	)
    );
    $query = new WP_Query( $args );

    But if I use this, do I create a custom template for each category, of which there are going to be lots?

    Hello,

    Try this code in category.php

    <?php
    	$get_current_cat = get_term_by('name', single_cat_title('',false), 'category');
    	$current_cat = $get_current_cat->term_id;
    
    	// List posts by the terms for a custom taxonomy of any post type
    	$post_type = 'myposttype';
    	$tax = 'mytaxonomy';
    	$tax_terms = get_terms( $tax, 'orderby=name&order=ASC');
    	if ($tax_terms) {
    		foreach ($tax_terms  as $tax_term) {
    			$args = array(
    				'post_type'			=> $post_type,
    				"$tax"				=> $tax_term->slug,
    				'post_status'		=> 'publish',
    				'posts_per_page'	=> -1,
    				'category__in'		=> $current_cat
    			);
    
    			$my_query = null;
    			$my_query = new WP_Query($args);
    
    			if( $my_query->have_posts() ) : ?>
    
    				<div class="clearfix">
    					<h2><?php echo $tax_term->name; ?></h2>
    
    					<?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
    
    						<?php $term_list = wp_get_post_terms($post->ID, 'category', array("fields" => "ids")); ?>
    						<?php if (in_array($current_cat, $term_list) ): ?>
    
    							<h3><?php the_title(); ?></h3>
    
    						<?php endif; // if in_array ?>
    
    					<?php endwhile; // end of loop ?>
    				</div>
    
    			<?php endif; // if have_posts()
    			wp_reset_query();
    
    		} // end foreach #tax_terms
    	} // end if tax_terms
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Group Posts by Taxonomy on Category pages’ is closed to new replies.
Skip to toolbar