Skip to content

Instantly share code, notes, and snippets.

@cwulff
Created July 23, 2013 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwulff/6063784 to your computer and use it in GitHub Desktop.
Save cwulff/6063784 to your computer and use it in GitHub Desktop.
Group and order custom posts by custom taxonomy
<?php
/*
Group and order custom posts by custom taxonomy
http://www.pauljoyceuk.com/codex/2013/how-to-group-wordpress-posts-by-custom-taxonomy
Change the following two lines to allow for your custom
taxonomy and the post type that uses it
*/
$taxonomy = array( "name" => "country" , "slug" => "country");
$custom_post_type = "pjuk_project";
if ( have_posts() )
the_post();
?>
<?php
// Query your specified taxonomy to get, in order, each category
$categories = get_terms($customTaxonomy['name'], 'orderby=title');
foreach( $categories as $category ) {
?>
<div id="content" class="<?php echo strtolower($category->name); ?>">
<!-- Output the category name as a H1, linking to its specified URL -->
<h1 class="page-title"><span>
<a href="/<?php echo $taxonomy["slug']; ?>/<?php echo $category->slug; ?>'>
<?php echo $category->name; ?>
</a>
</span></h1>
<?php
// Setup query to return each custom post within this taxonomy category
$o_queried_posts = get_posts(array(
'nopaging' => true,
'post_type' => $custom_post_type,
'taxonomy' => $category->taxonomy,
'term' => $category->slug,
));
?>
<div id='archive-content'>
<?php
// Loop through each custom post type
foreach($o_queried_posts as $o_post) {
setup_postdata($o_post); // Helps to format custom query results for using Template tags. See links in article for further explanation
?>
<div id="post-<?php the_ID(); ?>" <?php post_class($custom_post_type); ?>>
<!-- Layout the post type excerpt as you see fit by modifying the next block -->
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr( 'Permalink to %s' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<div class="archive-excerpt">
<?php the_excerpt(); ?>
</div><!-- .archive-excerpt -->
</div><!-- #post -->
<?php } // foreach($o_queried_posts as $o_post) ?>
</div> <!-- archive-content -->
</div> <!-- #content -->
<?php } // foreach( $categories as $category ) ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment