Skip to content

Instantly share code, notes, and snippets.

@antcms
Created June 16, 2016 03:48
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 antcms/a62af04defa75a15f6389097cdb707da to your computer and use it in GitHub Desktop.
Save antcms/a62af04defa75a15f6389097cdb707da to your computer and use it in GitHub Desktop.
Sort and display WordPress custom post types by taxonomy on Archive or Page
<?php get_header(); ?>
<h1><?php post_type_archive_title(); ?></h1>
<!-- Set Up Page Anchors -->
<div>
<ul>
<li>Jump to:</li>
<?php
$custom_terms = get_terms('termname'); // Taxonomy
foreach($custom_terms as $custom_term) {
$anchor = $custom_term->slug;
$title = $custom_term->name;
?>
<li><a href="#<?php echo $anchor; ?>"><?php echo $title; ?></a></li>
<?php
}
?>
</ul>
</div>
<!-- Get the custom posts by term and display -->
<div>
<?php
$custom_terms = get_terms('termname'); // Taxonomy
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array('post_type' => 'posttype', // Post Type
'tax_query' => array(
array(
'taxonomy' => 'termname', // Taxonomy
'field' => 'slug',
'terms' => $custom_term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
?>
<section>
<h2 id="<?php echo $custom_term->slug; ?>"><?php echo $custom_term->name; ?></h2>
<?php
while($loop->have_posts()) : $loop->the_post();
?>
<div>
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>">View <?php the_title(); ?> $raquo;</a></p>
</div>
<?php
endwhile;
}
?>
</section>
<?php
endif;
}
?>
</div>
<?php get_footer(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment